Magento 2-保持产品图像长宽比


8

我正在使用Magento 2类别页面。

但是我不知道如何保持产品图像的宽高比。

在magento 1.x中,我可以获取图像src以使用以下代码。

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

但是在magento 2中,我可以在/app/design/frontend/Magento/luma/etc/view.xml文件中设置图像大小。

<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>

我试图用“自动”输入高度,但是没有用。

我也尝试只输入宽度,但是它也没有用。

而且我在Magento_Catalog / templates / product / list.phtml文件中找到了以下用于显示产品图片的代码。

<?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>

有谁知道如何在保持商品图片高宽比的情况下显示商品图片?

Answers:


9

您可以使用以下代码。

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

您能解释@Dmitry和@SH Patel之间的代码差异吗?
Suresh Chikani 2015年

为此+1。使用此功能,您还可以在电子邮件模板中调整图像大小。
Chirag Parmar

2

您可以使用图像助手在magento2(如magento 1.x)中设置“保留产品图像长宽比”。

您可以在列表文件中使用这样的图像帮助程序: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'); ?>" />

我们应该在resize()功能中将高度优先还是宽度优先?
Magento Learner
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.