You may require to import product images in Magento 2 while migrating the website data or require to get the product image URL to fetch product images, implement custom functionality or developing some features. Today, I’ve come up with the solution to get product image URL in Magento 2.
Steps to get product image URL in Magento 2:
<?php 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; } }
That’s all about getting Magento 2 product image URL. Let me know if you have any query regarding it by commenting down below! If the tutorial has helped you enough, don’t forget to rate and share it with other Magento community members.