How to Resize Product Images Programmatically in Magento 2
In this article we'll discuss how to resize product images programmatically in Magento 2. As we know resizing product images programmatically in Magento 2 entails making use of Magento's built-in functions and features. You can accomplish this by writing your own script or module. The steps for resizing product photos programmatically are listed below.
Step 1: Create a Custom Module (if needed)
If you don't have a custom module already, you need to create one module. If you already have a module then go with that. If you are new to Magento then check our another article How To Create a Magento 2 Module.
Step 2: Create Class or Function
Within your custom module, create a script or function that retrieves the product image and resizes it.
In this atricle will create a helper class Data.php file at app/code/Devhooks/ModuleName/Helper and paste the below code.
saveCopyzoom_out_map<?php
namespace Devhooks\ModuleName\Helper;
use Magento\Catalog\Helper\Image;
use Magento\Catalog\Model\ProductRepository;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
class Data extends AbstractHelper
{
private ProductRepository $productRepository;
private Image $productImage;
/**
* @param Context $context
* @param ProductRepository $productRepository
* @param Image $productImage
*/
public function __construct(
Context $context,
ProductRepository $productRepository,
Image $productImage
) {
parent::__construct($context);
$this->productRepository = $productRepository;
$this->productImage = $productImage;
}
/**
* @param int $productId
* @param string $imageType
* @param int $imagewidth
* @param int $imageheight
* @return string
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function getResizeProductImage(
$productId,
$imageType = 'thumbnail',
$imagewidth = 100,
$imageheight = 100
) {
$product = $this->productRepository->getById($productId);
$imageUrl = $this->productImage->init($product, $imageType);
$imageUrl->setImageFile($product->getImage());
$imageUrl->resize($imagewidth, $imageheight)->getUrl();
return $imageUrl;
}
}
In the above code, we have created a helper class with getResizeProductImage method. You can injecte the helper class whereever you need and use the getResizeProductImage method and pass the required parameters.
Step 3: Open Command line in folder root of magento and run commands for create new customer attribute programmatically.
saveCopyzoom_out_mapphp bin/magento setup:upgrade php bin/magento cache:clean
Bingo!! we are done.
I hope this article helped you to find what you were looking for.
Bookmark it for your future reference. Do comment below if you have any other questions on that.
P.S. Do share this article with your team.