Home » Magento, Magento 216 June 2016

Magento 2: Resize Image

This article shows how to resize product image in Magento 2. In this example, we will be loading a product by id or sku and then resizing its image. We will also be injecting the object of Catalog Helper Image class for image resize purpose.

To load the product, we will be using Magento 2’s Service Layer for this task. Use of Service Layer is highly encouraged by Magento.

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


We resize the product base image to certain height and width. We have kept the image constrain, aspect ratio, and transparency to TRUE. keepFrame is set as false.

constrainOnly: Guarantee, that image picture will not be bigger, than it was. It is false by default.

keepAspectRatio: Guarantee, that image picture width/height will not be distorted. It is true by default.

keepTransparency: Guarantee, that image will not lose transparency if any. It is true by default.

keepFrame: Guarantee, that image will have dimensions, set in $width/$height. Not applicable, if keepAspectRatio(false).

Now, we load the product in template file. Then, we resize the product’s image and then display it. In the example below, we have used product_base_image as image ID. We can also use other ids like product_small_image, product_thumbnail_image, and so on if needed.

Directly resizing product image in template file

In the example above, I have injected product repository and image helper class in my custom HelloWorld block. You can also use it directly in your template (.phtml) file. Here is how to do so:

Open your template file and write the following code:

Hope this helps. Thanks.

Magento 2

Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed
  • Saurabh Misra

    Hello Mukesh , I want resize category banner images , I am using this block but category banner image not resized . What i do ? please suggest me