Magento 2:获取图像的高度和宽度
Magento 2获取图像的高度和宽度。Magento 2:获取图像的高度和宽度,magento,magento2,Magento,Magento2,Magento 2获取图像的高度和宽度。 产品图像我需要定义图像的高度和宽度。您可以使用下面提到的代码在模板中获得完整的产品图像路径: app/code/Chapagain/HelloWorld/Block/HelloWorld.php <?php namespace Chapagain\HelloWorld\Block; class HelloWorld extends \Magento\Framework\View\Element\Template { protecte
产品图像我需要定义图像的高度和宽度。您可以使用下面提到的代码在模板中获得完整的产品图像路径:
app/code/Chapagain/HelloWorld/Block/HelloWorld.php
<?php
namespace Chapagain\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $_productRepository;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ProductRepository $productRepository,
array $data = []
)
{
$this->_productRepository = $productRepository;
parent::__construct($context, $data);
}
public function getProductById($id)
{
return $this->_productRepository->getById($id);
}
public function getProductBySku($sku)
{
return $this->_productRepository->get($sku);
}
/**
* Retrieve image width
*
* @return int|null
*/
public function getImageOriginalWidth($product, $imageId, $attributes = [])
{
return $this->_productImageHelper->init($product, $imageId, $attributes)->getWidth();
}
/**
* Retrieve image height
*
* @return int|null
*/
public function getImageOriginalHeight($product, $imageId, $attributes = [])
{
return $this->_productImageHelper->init($product, $imageId, $attributes)->getHeight();
}
}
?>
echo $block->getImage($_product, $image)->getImageUrl();
它将返回完整的图像路径,包括Magento 2产品的缓存图像路径
但是,如果还需要获取图像高度和宽度,可以使用以下代码:
echo $block->getImage($_product, $image)->getHeight();
它将返回图像高度
echo $block->getImage($_product, $image)->getWidth();
并且,它将帮助您返回图像宽度
echo $block->getImage($_product, $image)->getHeight();
echo $block->getImage($_product, $image)->getWidth();