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?

asked Nov 6, 2020 at 0:00

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"/>
answered Nov 6, 2020 at 0:53
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? Commented Nov 6, 2020 at 1:39
  • use the second method from my answers. Commented Nov 9, 2020 at 0:11

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.