1

What is the best way to get product image(thumbnail) by sku ?

1
  • Add more details about your task and what want to achieve – Jarnail S Feb 18 at 12:49
0

This way the best way to get a product image.

protected $_productRepository;

public function __construct(
 \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
) {            
    $this->_productRepository = $productRepository;
}

Get image like this:

$product = $this->_productRepository->get($sku); //pass sku here
$product->getData('thumbnail');
2
  • Thanks for the answer. – Hamendra Sunthwal Feb 18 at 12:38
  • if you getting any error let me know :) – Rk Rathod Feb 18 at 12:41
1

1)Create a block file:

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

2)Create custom template file:

$url=$block->getProductImageUrl($id);
0
$product = $this->_productRepositoryFactory->create()->getBySku($sku);
$product->getData('image');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.