Request Quote Demos

Resize Product Image in Magento 2

Today we are discussing how to resize the product image in Magento 2.
To get this you can use the following code:

<?php
/**
 *
 * @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.

Hope it will help you. Thank you.

. . .

Comment

Add Your Comment

Be the first to comment.

css.php