How to resize product image in magento 2?

To resize product images in Magento 2, You need to refer to the code snippet for resizing product images at any place in the file.

Magento Class file Magento\Catalog\Helper\Image is used to resize the product image.

Call Init() function and pass parameters,

The first parameter is the $product Object,
The second parameter is the product id, You can be called any product id like thumbnail, or small_image (Check the list of image id under the theme etc/view.xml file)
The third parameter as array is optional,

For Custom Image resizing refer to the blog, Resize the custom image in Magento 2

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
public function __construct(
private ImageHelper $imageHelper
) {
}
public function getResizeImage() {
$product = $productObject; // Fetch Product Object
$productImageUrl = $this->imageHelper->init($product, 'thumbnail')
->setImageFile($product->getThumbnail())
->resize('256','128')
->getUrl();
return $productImageUrl;
}
<?php public function __construct( private ImageHelper $imageHelper ) { } public function getResizeImage() { $product = $productObject; // Fetch Product Object $productImageUrl = $this->imageHelper->init($product, 'thumbnail') ->setImageFile($product->getThumbnail()) ->resize('256','128') ->getUrl(); return $productImageUrl; }
<?php
    public function __construct(
        private ImageHelper $imageHelper
    ) {
    }
    
    public function getResizeImage() {
    $product = $productObject; // Fetch Product Object

    $productImageUrl = $this->imageHelper->init($product, 'thumbnail')
               ->setImageFile($product->getThumbnail())
               ->resize('256','128')
               ->getUrl();
        return $productImageUrl;        
    }

Here setImageFile() method is optional and if you don’t pass the value it will take it from the product thumbnail.

Return Product resizes URL as output.