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.

app/code/Chapagain/HelloWorld/Block/HelloWorld.php


<?php
namespace Chapagain\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{	
	protected $_productRepository;
	protected $_productImageHelper;
		
	public function __construct(
		\Magento\Backend\Block\Template\Context $context,		
		\Magento\Catalog\Model\ProductRepository $productRepository,
		\Magento\Catalog\Helper\Image $productImageHelper,
		array $data = []
	)
	{
		$this->_productRepository = $productRepository;
		$this->_productImageHelper = $productImageHelper;
		parent::__construct($context, $data);
	}
	
	public function getProductById($id)
	{
		return $this->_productRepository->getById($id);
	}
	
	public function getProductBySku($sku)
	{
		return $this->_productRepository->get($sku);
	}
	
	/**
     * Schedule resize of the image
     * $width *or* $height can be null - in this case, lacking dimension will be calculated.
     *
     * @see \Magento\Catalog\Model\Product\Image
     * @param int $width
     * @param int $height
     * @return $this
     */
    public function resizeImage($product, $imageId, $width, $height = null)
    {
        $resizedImage = $this->_productImageHelper->init($product, $imageId)
										   ->constrainOnly(TRUE)
										   ->keepAspectRatio(TRUE)
										   ->keepTransparency(TRUE)
										   ->keepFrame(FALSE)
										   ->resize($width, $height);
		return $resizedImage;
    }	
}
?>

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.


<?php
$id = YOUR_PRODUCT_ID;
$_product = $block->getProductById($id);
// $sku = 'YOUR_PRODUCT_SKU';
// $_product = $block->getProductBySku($sku);

$imageId = 'product_base_image';
$width = 200;
$height = 300;

$resizedImageUrl = $block->resizeImage($product, 'product_base_image', $width, $height)->getUrl();
?>
<img src="$resizedImageUrl" alt="product image" />

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:


<?php
$id = YOUR_PRODUCT_ID;
$_product = $block->getProductById($id);
// $sku = 'YOUR_PRODUCT_SKU';
// $_product = $block->getProductBySku($sku);

$imageId = 'product_base_image';
$width = 200;
$height = 300;

$resizedImageUrl = $_imageHelper->init($product, $imageId)
								->constrainOnly(TRUE)
							    ->keepAspectRatio(TRUE)
							    ->keepTransparency(TRUE)
							    ->keepFrame(FALSE)
							    ->resize($width, $height)
							    ->getUrl();
?>
<img src="$resizedImageUrl" alt="product image" />

Hope this helps. Thanks.