Get Product Small Image Url Using Product id. You can retrieve small_image Url of the product.
You need to instantiate the ImageFactory to load image objects using Magento\Catalog\Helper\ImageFactory.
Check the code snippet to retrieve Image Url,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | <?php namespace Jesadiya\ProductSmallImage\Model; use Exception; use Psr\Log\LoggerInterface; use Magento\Catalog\Helper\ImageFactory; use Magento\Catalog\Api\ProductRepositoryInterface; class ImageUrl { /** * Small image value. * * @var string */ const SMALL_IMAGE = 'small_image'; /** * @var ImageFactory */ public $imageFactory; /** * @var LoggerInterface */ public $logger; public function __construct( ImageFactory $imageFactory, ProductRepositoryInterface $productRepository, LoggerInterface $logger ) { $this->imageFactory = $imageFactory; $this->productRepository = $productRepository; $this->logger = $logger; } /** * Get Image url * * @return string */ public function getImageUrl() { $productId = 1; $imageUrl = null; try { $product = $this->productRepository->getById($productId); if ($product) { $imageHelper = $this->imageFactory->create()->init($product, self::SMALL_IMAGE); $imageUrl = $imageHelper->getUrl(); } } catch (Exception $exception) { $this->logger->error($exception->getMessage()); } return $imageUrl; } } |
You can get Product small_image URL by product id by referring the above code.