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?

8

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; ?>" />
  • Can you explain code diffrences between @Dmitry and @S H Patel ? – Suresh Chikani Oct 8 '15 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'); ?>" />
  • Should we put height first og width first in the resize() function? – Magento Learner Sep 17 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.