如果您需要调整产品图像的大小并使用默认的Magento图像缓存系统,并且您不在前端区域中,则可以使用此替代方法。
用例:如果需要在自定义API上为外部应用程序调整图像URL的大小,这可能会很有用。
功能码:
/**
* @var \Magento\Catalog\Model\ProductFactory
*/
protected $productFactory;
/**
* @var \Magento\Catalog\Helper\ImageFactory
*/
protected $helperFactory;
/**
* @var \Magento\Store\Model\App\Emulation
*/
protected $appEmulation;
/**
* Constructor.
*
* @param \Magento\Catalog\Model\ProductFactory $productFactory
* @param \Magento\Store\Model\App\Emulation $appEmulation
* @param \Magento\Catalog\Helper\ImageFactory $helperFactory
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
*/
public function __construct(
\Magento\Catalog\Model\ProductFactory $productFactory,
\Magento\Store\Model\App\Emulation $appEmulation,
\Magento\Catalog\Helper\ImageFactory $helperFactory,
\Magento\Store\Model\StoreManagerInterface $storeManager,
) {
$this->productFactory = $productFactory;
$this->imageBuilder = $imageBuilder;
$this->helperFactory = $helperFactory;
$this->appEmulation = $appEmulation;
$this->storeManager = $storeManager;
}
/**
* Retrieve product image
*
* @param \Magento\Catalog\Model\Product $product
* @param string $imageId
* @param array $attributes
* @return \Magento\Catalog\Block\Product\Image
*/
public function getImage($product, $imageId, $attributes = [])
{
$image = $this->helperFactory->create()->init($product, $imageId)
->constrainOnly(true)
->keepAspectRatio(true)
->keepTransparency(true)
->keepFrame(false)
->resize(200, 300);
return $image;
}
public function customFunction()
{
// some stuff here
$storeId = $this->storeManager->getStore()->getId();
$this->appEmulation->startEnvironmentEmulation($storeId, \Magento\Framework\App\Area::AREA_FRONTEND, true);
$product = $this->productFactory->create()->loadByAttribute('sku', 'productSKU');
$imageUrl = $this->getImage($product, 'product_base_image')->getUrl();
echo $imageUrl;
$this->appEmulation->stopEnvironmentEmulation();
// some stuff here
}
输出示例:
http://{domain}/media/catalog/product/cache/1/image/200x300/e9c3970ab036de70892d86c6d221abfe/s/r/{imageName}.jpg
评论 :
如果您已经在同一storeId上,则函数startEnvironmentEmulation的第三个参数用于强制使用前端区域。(对API区域有用)
此解决方法可以避免出现此类错误:
http://XXXX.com/pub/static/webapi_rest/_view/en_US/Magento_Catalog/images/product/placeholder/.jpg
Uncaught Magento\Framework\View\Asset\File\NotFoundException: Unable to resolve the source file for 'adminhtml/_view/en_US/Magento_Catalog/images/product/placeholder/.jpg'