0

How is the right way of resizing images in Magento 2.

$image->getData('url');

I have the url of the image, how to resize it using the url? Is there an API / helper that does that?

1 Answer 1

0

This should help you if you have $_product object:

$_imagehelper = $this->helper('Magento\Catalog\Helper\Image');
$image = 'category_page_grid'; //from theme's etc/view.xml
//if you want aspect ration
//$aspect_ratio = true; $image_width = 200, $image_height = 300;
if($aspect_ratio) {
    $productImage = $_imagehelper->init($_product, $image)->constrainOnly(FALSE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->resize($image_width);
} else {
    $productImage = $_imagehelper->init($_product, $image)->resize($image_width, $image_height);
    $productImageUrl = $productImage->getUrl();
}

If you have just got URL then using img style would be enough:

<img src="<?= $img->getData('url');?>" width="200"/>
2
  • I have the image URL and because I want to resize my gallery images and not just one product image. is there any way to do that? Nov 6, 2020 at 1:39
  • use the second method from my answers. Nov 9, 2020 at 0:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.