Magento 2 – How to Keep Product Image Aspect Ratio

magento2

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?

Best Answer

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; ?>" />
Related Topic