Magento – How to crop (not just resize) images with view.xml

imagemagento2product-images

I have this in my view.xml:

<image id="new_products_content_widget_grid" type="small_image">
    <width>474</width>
    <height>267</height>
    <aspect_ratio>true</aspect_ratio>
    <frame>false</frame>
</image>

And this in my template:

<?php echo $block->getImage($_product, $image)->toHtml();?>

Where $_product comes from $_productCollection = $block->getLoadedProductCollection();

The uploaded images are square, but the design wants them to be output as a rectangle. With XML above, I get squares with vertical letterboxing.

enter image description here

How do I go about having the image enlarged to fill the entire rectangle, by cropping top and bottom off the image?

Best Answer

Came here for an answer, but alas. It's a problem with the <frame>false</frame> setting and is acknowledged as a bug (#4622). We can work around it because most of our images have a fixed size ratio, so we'll just wait for the fix to come through.

Though, it seems to be possible to work around the issue by calling these settings in your phtml file where you list your thumbnails:

<?php
   $_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; ?>" />

As mentioned in this answer.

Edit: I've just applied the same fix in my /product/list.phtml and it's working like a charm!

Related Topic