HOW TO RESIZE IMAGES IN MAGENTO 2?

Why we need to resize the image when we can overwrite original images?

When a developer works on custom modules having images, he/she would want to fetch products or category images. They may face problems with image being displayed in different sizes on the frontend. This situation can be resolved in two ways: First is using CSS but this is not advisable. Second option is resizing the actual image and save it to the cache folder.

What are the benefits of resizing the actual image file instead of using CSS to resize them in HTML?

If there is a huge difference in the source and target image sizes, the default resizing utility offered by CSS cannot be used. One can resize the entire image or retain only its central part to achieve the desired results.

How to resize the actual image in Magento 2?

In this blog, I am going to explain how to save resized image to a cache folder and every time it returns the image when requested and it won’t overwrite the original image.

For instance, you’ve added 400*300 sized image for a product category and you want that particular category to be displayed on home page with a size 256*180. It may not be a viable solution to resize the original file each time. Hence, designer would add the resized image that is 256*180 in the cache folder. Each time when request is sent, it returns the image from cache. One can call it from any class, template, or block.

Step 1: You need to create helper class file Image.php at VenderModuleHelperImage.php and the past below code.
[xml]< ?php
namespace VenderModuleHelper;
use MagentoFrameworkFilesystem;
use MagentoFrameworkUrl;
use MagentoFrameworkAppHelperAbstractHelper;
use MagentoFrameworkAppFilesystemDirectoryList;
class Image extends MagentoFrameworkAppHelperAbstractHelper {
protected $scopeConfig;
protected $storeManager;
protected $messageManager;
protected $_response;
protected $_resourceConfig;
protected $_responseFactory;
protected $_url;
protected $_filesystem;
protected $_directory;
protected $_imageFactory;
public function __construct(
MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkMessageManagerInterface $messageManager,
MagentoFrameworkAppResponseInterface $response,
MagentoFrameworkAppConfigStorageWriterInterface $resourceConfig,
MagentoFrameworkAppResponseFactory $responseFactory,
MagentoFrameworkUrlInterface $url,
MagentoFrameworkFilesystem $filesystem,
MagentoFrameworkImageAdapterFactory $imageFactory
)
{
$this->scopeConfig = $scopeConfig;
$this->_storeManager=$storeManager;
$this->messageManager=$messageManager;
$this->_response=$response;
$this->_resourceConfig=$resourceConfig;
$this->_responseFactory = $responseFactory;
$this->_url = $url;
$this->_filesystem = $filesystem;
$this->_directory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$this->_imageFactory = $imageFactory;
}
public function imageResize(
$src,
$width=35,
$height=35,
$dir=’resized/’
){
$absPath = $this->_filesystem
->getDirectoryRead(DirectoryList::MEDIA)
->getAbsolutePath().$src;
$imageResized = $this->_filesystem
->getDirectoryRead(DirectoryList::MEDIA)
->getAbsolutePath($dir).
$this->getNewDirectoryImage($src);
$imageResize = $this->_imageFactory->create();
$imageResize->open($absPath);
$imageResize->backgroundColor([255, 255, 255]);
$imageResize->constrainOnly(TRUE);
$imageResize->keepTransparency(TRUE);
$imageResize->keepFrame(true);
$imageResize->keepAspectRatio(true);
$imageResize->resize($width,$height);
$dest = $imageResized ;
$imageResize->save($dest);
$resizedURL= $this->_storeManager->getStore()
->getBaseUrl(MagentoFrameworkUrlInterface::URL_TYPE_MEDIA).
$dir.$this->getNewDirectoryImage($src);
return $resizedURL;
}
public function getNewDirectoryImage($src){
$segments = array_reverse(explode(‘/’,$src));
$first_dir = substr($segments[0],0,1);
$second_dir = substr($segments[0],1,1);
return ‘cache/’.$first_dir.’/’.$second_dir.’/’.$segments[0];
}
}
[/xml]
Step 2: Using below code you can call above imageResize() method from any class, block or
[xml]$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$imgpath = $objectManager-&gt;create(‘VenderModuleHelperImage’)-&gt;imageResize(‘IMAGE_PATH’,’50’,’50’,’YOUR_DIR_NAME/’);[/xml]
Here you got the output as 50×50 Resize image. Now I am going to explain the methods I have used

1. getDirectoryRead() : While building your custom extension, you will usually need a path to your extension’s files. However, sometimes you will need to get a root folder or maybe to media folder.

2. getAbsolutePath() : here you will be able to get the absolute path to save cache. We have to pass folder name in the parameter.

3. backgroundColor(): used to set background color

4. constrainOnly():br ?–> constrainOnly(true): This will not resize an image that is smaller than the dimensions inside the resize() part. The default value is true in Magento 2

constrainOnly(false): This will resize an image that is smaller than the dimensions inside the resize() part

5. keepTransparency(): By default it is True, that means the image will not lose transparency.

6. keepFrame(): keepFrame(true): Properly remove white image frame upon resizing photos in Magento

keepFrame(false): Properly doesn’t remove white image frame upon resizing photos in Magento

7. keepAspectRatio(): keepAspectRatio(true): It maintains the ratio. if a graphic has an aspect ratio of 2:1, it means that the width is twice as large as the height. When resizing graphics, it is important to maintain the aspect ratio

keepAspectRatio(false): It doesn’t maintain the ratio.

Magento 2 – Properly remove white image from frame

[xml]< ?php foreach ($this->getGalleryImages() as $_image): ?>
<li>
<a href=”#” onclick=”popWin(‘<?php echo $this->getGalleryUrl($_image) ?>’, ‘gallery’, ‘width=300,height=300,left=0,top=0,location=no,status=yes,scrollbars=yes,resizable=yes’); return false;” title=”< ?php echo $this->htmlEscape($_image->getLabel()) ?>”><img class=”lazyload” data-src=”<?php echo $this-/><noscript><img class=”lazyload” data-src=”<?php echo $this-/><noscript><img src=”<?php echo $this-/></noscript></noscript>helper(‘catalog/image’)->init($this->getProduct(), ‘thumbnail’, $_image->getFile())->keepFrame(false)->resize(56); ?>” alt=”< ?php echo $this->htmlEscape($_image->getLabel()) ?>” /></a>
</li>
< ?php endforeach; ?>[/xml]
Releted – How to Create a Shipping Method in Magento 2
Resize Product Images in Magento 2
We would discuss the ways in which you can resize the product images in Magento 2. You can use the following code:
[xml]<?php
/**
*
* @var MagentoCatalogModelProductRepository
*/
protected $_productRepository;

/**
*
* @var MagentoCatalogHelperImage
*/
protected $_productImageHelper;

/**
* @param MagentoBackendBlockTemplateContext $context
* @param MagentoCatalogModelProductRepository $productRepository
* @param MagentoCatalogHelperImage $productImageHelper
* @param array $data
*/
public function __construct(
MagentoBackendBlockTemplateContext $context,
MagentoCatalogModelProductRepository $productRepository,
MagentoCatalogHelperImage $productImageHelper,
array $data = []
)
{
$this->_productRepository = $productRepository;
$this->_productImageHelper = $productImageHelper;
parent::__construct($context, $data);
}

/**
* resize of the image
* @see MagentoCatalogModelProductImage
* @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;
}
[/xml]

In this case, $_productRepository is an object of MagentoCatalogModelProductRepository class and $_productImageHelper is an object of MagentoCatalogHelperImage class.

In the Function resizeImage, there are 4 major 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.

Helpful Blog reading – How to Configure Shipping Methods in Magento 2

Set quality product images in Magento 2

If you want to reduce quality of product images for different purposes such as improve site’s performance, improve user’s experience, have you ever questioned how to set quality of Magento catalog product images directly in template files?

You would not have to duplicate the core files. Without editing the adapters, you can change the size of images. SetQuality is a new method that can be implemented and used for template files. For instance: If you need to improve quality of product images, you can open:-

app/design/frontend/yourpackage/yourtheme/template/catalog/product/list.phtml and add ->setQuality(100) in the end of img src as follows:

[xml]<img src=”<?php echo $this->helper(‘catalog/image’)->init($_product, ‘small_image’)->resize(122,180)->setQuality(100); ?>” alt=”” /></code>[/xml]

Once you have good quality product images, you can empty the cache of images via System> Cache Management.

How to get product image URL in Magento 2?

By default, the properties of product images are stored in view.xml configuration file. They can be defined by gallery widget and can be altered in the theme view.xml file.

i-Verve is a leading Magento development services provider company that deploys online stores to this popular e-commerce platform in the best way.