ques-9M9VlO28

Search A2Z 24

Question : Magento 2 - Keep Product Image Aspect Ratio

X

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</heigh>
</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(); ?>

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

 

asked October 11, 2016

1 Answers

Dispalying 1 to 1 of 1 |

Use below code :


<?php
    //$image = "category_page_grid" or "category_page_list";
    $_imagehelper = $this->helper("MagentoCatalogHelperImage");

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

<img src="<?php echo $productImage; ?>" />


See comments (0) | Comment
Answered 2 Years ago
Dispalying 1 to 1 of 1 |

Write your Answer write code <pre class="brush: xml">---code---</pre>

Login as a member to access answering block !! click-here
loading...

×