Hello Magento Folks?,
Welcome to Magento How-To Blog. Today I will illustrate Magento 2 Regenerate Catalog Product Cache Images Programmatically. Lastly, we learned How To Get Formatted Price With Currency In Magento 2. Let’s Get In?.
Introduction:
Basically, Magento 2 generates different types of catalog images while creating some products from admin. e.g : small_image , thumbnail_image , base_image etc. It also generates some images with a cache folder too. But in some cases, many cache images are not generated e.g. while upgrading the Magento version, server transfer and especially use third party media storage. The reason is Magento 2 does not generate product page cache images while we are using third party media storage hence for that we need to run the resize command. But it is a very time-consuming process. And to overcome this problem here we have come up with an easy solution. You can regenerate catalog product cache images programmatically as per your need.
Steps to Regenerate Catalog Product Cache Images Programmatically:
Step 1: Firstly, we require to just update the gallery.phtml file at the following path,
vendor\magento\module-catalog\view\frontend\templates\product\view and add below code at the First line of file.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $resizeImage = $objectManager->get('\Magento\MediaStorage\Service\ImageResize'); $_product = $block->getProduct(); $galleryImages = $_product->getMediaGalleryImages(); if ($galleryImages) { foreach ($galleryImages as $image) { $resizeImage->resizeFromImageName($image->getFile()); } }
Note: One can update the file path based on your theme.
Step 2: After that refresh the cache.
That’s It.
Over to you:
Hopefully, all have implemented successfully the above steps for Regenerate Catalog Product Cache Images Programmatically in Magento 2. But if you face any problems in this do write it in the comment section below. If you find the article helpful then share it with your Magento developer friends. Let’s meet in the next blog.
Happy Developing?