Resize Product Image in Magento 2

magento-prashantblog-520x245

Today We are going to describe how to resize the product image in Magento 2. Product image size is the good attribute to make your goods closer to the consumer with the product details. This article shows how to resize product image in Magento 2. In this example, I am loading a product by id and then resizing its image. I will also be injecting the object of Catalog Helper Image class for image resize purpose.

Below is a block class of my custom module (Prashant_Common). I have injected an object of \Magento\Catalog\Model\ProductRepository and \Magento\Catalog\Helper\Image class in the constructor of my module’s block class.


app/code/Prashant/Common/Block/Resize.php

To get this you can use the following code:

Here, $_productRepository is an object of Magento\Catalog\Model\ProductRepository class and $_productImageHelper is an object ofMagento\Catalog\Helper\Image class.



And in the Function resizeImage, there are four parameters $id this is id of the product, $image_type that can “product_base_image” or “product_small_image”,”product_thumbnail_image” and $width, $height is width and height of the image respectively.





constrainOnly-> By default it is False. but if we set True that means the image will not bigger than it was.
keepAspectRatio-> By default it is True, that means image height and width will not be contorted.
keepFrame-> keepFrame(False) will remove the background and set the image to desired width/height.
keepTransparency-> By default it is True, that means the image will not lose transparency.


Related posts

Leave a Comment