Magento开发之获取产品图片url

更新

首先,注入 \Magento\Catalog\Api\ProductRepositoryInterfaceFactory 到 constructor


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');

其他方法:


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


<?php
namespace namespace Vendor\Extension\Block;
use Magento\Framework\View\Element\Template;
use Magento\Catalog\Helper\Image;
use Magento\Catalog\Model\ProductFactory;
use Magento\Framework\View\Element\Template\Context;
class Extension extends Template
{
    protected $imageHelper;
    protected $productFactory;
    public function __construct(Image $imageHelper, ProductFactory $productFactory, Context,) 
    {
        $this->imageHelper = $imageHelper;
        $this->productFactory = $productFactory;
    }
    public function getProductImageUrl($id)
    {
        try 
        {
            $product = $this->productFactory->create->load($id);
        } 
        catch (NoSuchEntityException $e) 
        {
            return 'Data not found';
        }
        $url = $this->imageHelper->init($product, 'product_thumbnail_image')->getUrl();
        return $url;
    }
}