8

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.

<?php echo $this->helper('catalog/image') ->init($_product, 'small_image') ->constrainOnly(FALSE) ->keepAspectRatio(TRUE) ->keepFrame(FALSE) ->resize(300); ?> 

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"> <width>240</width> <height>300</height> </image> <image id="category_page_list" type="small_image"> <width>240</width> <height>300</height> </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.

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

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

2 Answers 2

12

You can use below code.

<?php //$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; ?>" /> 
1
  • Can you explain code diffrences between @Dmitry and @S H Patel ? Commented Oct 8, 2015 at 10:42
2

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'); ?>" /> 
1
  • Should we put height first og width first in the resize() function? Commented Sep 17, 2019 at 8:05

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.