Resize Product Image in Magento 2
Today I am 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:
<?php namespace Prashant\Common\Block; class Resize extends \Magento\Framework\View\Element\Template { /** * * @var \Magento\Catalog\Model\ProductRepository */ protected $_productRepository; /** * * @var \Magento\Catalog\Helper\Image */ protected $_productImageHelper; /** * @param \Magento\Backend\Block\Template\Context $context * @param \Magento\Catalog\Model\ProductRepository $productRepository * @param \Magento\Catalog\Helper\Image $productImageHelper * @param array $data */ 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); } /** * resize of the image * @see \Magento\Catalog\Model\Product\Image * @param int $width * @param int $height * @return $this */ public function resizeImage($id, $image_type, $width, $height = null) { $product = $this->_productRepository->getById($id); $resizedImage = $this->_productImageHelper->init($product, $image_type) ->constrainOnly(TRUE) ->keepAspectRatio(TRUE) ->keepTransparency(TRUE) ->keepFrame(FALSE) ->resize($width, $height); return $resizedImage; } }
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.