I'm working with Magento 2 Category Page.

But I couldn't know how to keep the product image aspect ratios.

In magento 1.x, I can get the image src to use below code.

    echo $this->helper('catalog/image')
    ->init($_product, 'small_image')

But in magento 2, I can set the image sizes in /app/design/frontend/Magento/luma/etc/view.xml file.

<image id="category_page_grid" type="small_image">
<image id="category_page_list" type="small_image">

I tried to input the height with "auto", but it didn't work.

I also tried to input only width, it didn't work, too.

And I found below code for showing product images in Magento_Catalog/templates/product/list.phtml file.

    $productImage = $block->getImage($_product, $image);
<a href="<?php echo $_product->getProductUrl() ?>" class="product photo product-item-photo" tabindex="-1">
    <?php echo $productImage->toHtml(); ?>

Anyone know how to show the product images with keep Image aspect ratios?


You can use below code.

    //$image = 'category_page_grid' or 'category_page_list';
    $_imagehelper = $this->helper('Magento\Catalog\Helper\Image');

    $productImage = $_imagehelper->init($_product, $image)->constrainOnly(FALSE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->resize(400)->getUrl();

<img src="<?php echo $productImage; ?>" />
  • Can you explain code diffrences between @Dmitry and @S H Patel ? Oct 8 '15 at 10:42
  • +1 for this. With this you can resize image in email templates also. Jan 21 '20 at 12:52

You can set "Keep Product Image Aspect Ratio" in magento2 like magento 1.x using image helper.

You can use image helper like this in list file : app\code\Magento\Catalog\view\frontend\templates\product\list.phtml

$_Imagehelper = $this->helper('Magento\Catalog\Helper\Image');

<img src="<?php echo $_Imagehelper->init($_product, 'small_image')->keepAspectRatio(true)->resize('height', 'width'); ?>" />
  • Should we put height first og width first in the resize() function? Sep 17 '19 at 8:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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