如何在Magento 2中获取产品图片和URL?


16

这是我的观察者:

public function execute(\Magento\Framework\Event\Observer $observer)
{
    $orderIds = $observer->getEvent()->getOrderIds();
    $order = $this->_orderRepositoryInterface->get($orderIds[0]);
    $items =$order->getAllVisibleItems();
    $productQuantity = array();
    $productPrice = array();
    $productName = array();
    $productIds = array();
    foreach($items as $item) {
        $productIds[]= $item->getProductId();
        $productName[]= $item->getSku(); 
        $productPrice[] = $item->getPrice();
        $productQuantity[]= floor($item->getQtyOrdered());
    }
}

如何从商品中获取商品图片和商品网址?


你抓到哪个事件?
Khoa TruongDinh,2016年

checkout_onepage_controller_success_action
Ramkishan Suthar

Answers:


23

这种方法可能不是获取产品形象的最佳方法。

注入\Magento\Catalog\Api\ProductRepositoryInterfaceFactory我们的构造函数。

protected $_productRepositoryFactory;

public function __construct(
        \Magento\Catalog\Api\ProductRepositoryInterfaceFactory $productRepositoryFactory
) {

    $this->_productRepositoryFactory = $productRepositoryFactory;
}

我们可以得到图像:

$product = $this->_productRepositoryFactory->create()->getById($item->getProductId());
$product->getData('image');
$product->getData('thumbnail');
$product->getData('small_image');

您的回答是正确的,但是如果购物车中有多个产品,该怎么办?我如何显示多个产品图像
Ramkishan Suthar

好吧,我知道了@khoa。如果我有一张以上的产品图片。非常感谢
Ramkishan Suthar '16

这是行不通的。返回的值是某种字符串,例如“ /w/s/wsh10-orange_main.jpg”
Hoang Trinh

2
@piavgh,这是图像的道路:pub/media/catalog/product
Khoa TruongDinh '16

1
所以我该如何在<img src =“” />属性中使用/w/s/wsh10-orange_main.jpg,以便可以加载实际图像
Lachezar Raychev

18

如果您想要特定商店视图的图像的发布/缓存前端URL(像我一样),这对我有用:

/**
 * @var \Magento\Store\Model\App\Emulation
 */
protected $appEmulation;

/**
 * @var \Magento\Store\Model\StoreManagerInterface
 */
protected $storeManager;

/**
 * @var \Magento\Catalog\Api\ProductRepositoryInterfaceFactory
 */
protected $productRepositoryFactory;

/**
 * @var \Magento\Catalog\Helper\ImageFactory
 */
protected $imageHelperFactory;

/**
 * @param \Magento\Store\Model\StoreManagerInterface $storeManager
 * @param \Magento\Store\Model\App\Emulation $appEmulation
 * @param \Magento\Catalog\Api\ProductRepositoryInterfaceFactory $productRepositoryFactory
 * @param \Magento\Catalog\Helper\ImageFactory $helperFactory
 */
public function __construct(
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    \Magento\Store\Model\App\Emulation $appEmulation,
    \Magento\Catalog\Api\ProductRepositoryInterfaceFactory $productRepositoryFactory,
    \Magento\Catalog\Helper\ImageFactory $imageHelperFactory
)
{
    $this->storeManager = $storeManager;
    $this->appEmulation = $appEmulation;
    $this->productRepositoryFactory = $productRepositoryFactory;
    $this->imageHelperFactory = $imageHelperFactory;
}

然后,在任何需要获取图像前端URL的位置:

$sku = "my-sku";
// get the store ID from somewhere (maybe a specific store?)
$storeId = $this->storeManager->getStore()->getId();
// emulate the frontend environment
$this->appEmulation->startEnvironmentEmulation($storeId, \Magento\Framework\App\Area::AREA_FRONTEND, true);
// load the product however you want
$product = $this->productRepositoryFactory->create()->get($sku);
// now the image helper will get the correct URL with the frontend environment emulated
$imageUrl = $this->imageHelperFactory->create()
  ->init($product, 'product_thumbnail_image')->getUrl();
// end emulation
$this->appEmulation->stopEnvironmentEmulation();

您可以选择除product_thumbnail_image:以外的其他图像类型:参考magento/theme-frontend-luma/etc/view.xml以获取可用产品图像的列表,或在view.xml文件中创建自己的图像。


1
WTF?:D
Lachezar Raychev '17

刚刚尝试了此解决方案,尽管返回的URL不存在并且字符串为空,但我没有收到任何错误。我已经尝试过使用“ product_base_image”,“ product_small_image”和“ product_thumbnail_image”,但都无法使用。你能告诉我吗?还是有一种有效的方法使用产品存储库来做到这一点?因为我已经在块中的其他地方加载了它。
Joshua Flood

11

如果您需要返回产品网址,则该网址应如下所示:

//todo get product object $product 

$objectManager =\Magento\Framework\App\ObjectManager::getInstance();
$helperImport = $objectManager->get('\Magento\Catalog\Helper\Image');

$imageUrl = $helperImport->init($product, 'product_page_image_small')
                ->setImageFile($product->getSmallImage()) // image,small_image,thumbnail
                ->resize(380)
                ->getUrl();
echo $imageUrl;

6

我就是那样的 它非常有效且干净:

1)首先,您需要注入以下类:

protected $_storeManager;
protected $_appEmulation;
protected $_blockFactory;

public function __construct(
    ...
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    \Magento\Framework\View\Element\BlockFactory $blockFactory,
    \Magento\Store\Model\App\Emulation $appEmulation)
{
    $this->_storeManager = $storeManager;
    $this->_blockFactory = $blockFactory;
    $this->_appEmulation = $appEmulation;
}

2)然后,使用以下代码创建一个getImageUrl方法:

protected function getImageUrl($product, string $imageType = '')
{
    $storeId = $this->_storeManager->getStore()->getId();

    $this->_appEmulation->startEnvironmentEmulation($storeId, \Magento\Framework\App\Area::AREA_FRONTEND, true);

    $imageBlock =  $this->_blockFactory->createBlock('Magento\Catalog\Block\Product\ListProduct');
    $productImage = $imageBlock->getImage($product, $imageType);
    $imageUrl = $productImage->getImageUrl();

    $this->_appEmulation->stopEnvironmentEmulation();

    return $imageUrl;
}

注意:仅当您从管理员API进行此调用时,才需要“ appEmulation”代码。否则,您将得到以下错误(或类似错误):

Unable to resolve the source file for 'webapi_rest/_view/en_AU/Magento_Catalog/images/product/placeholder/.jpg'

3)调用getImageUrl传递产品对象和所需的图像类型(基于view.xml文件)

...
$smallImage = $this->getImageUrl($productObject, 'product_page_image_small');
...

1

为了获得自定义图像网址,我使用了此代码。因此,如果图像不存在,它将加载默认的主题图像。

$product = $block->getProduct();

$productImageAttr = $product->getCustomAttribute('product_banner_image');

if ($productImageAttr && $productImageAttr->getValue() != 'no_selection') {

    $productImage = $this->helper('Magento\Catalog\Helper\Image')
    ->init($product, 'product_banner_image')
    ->setImageFile($productImageAttr->getValue());

    $imageUrl = $productImage->getUrl();

} else {

    $imageUrl = $this->getViewFileUrl('images/cat-img1.jpg'); // Theme/web/images

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