How to get product image URL in Magento 2?
28 February 2022

How to get product image URL in Magento 2?

Images allow customers to pay more attention and when it comes to an eCommerce store, showing product images to customers gives them more confidence and it is a must-do activity for an online store. In today's blog, we will illustrate how you can fetch product image URL in Magento 2.

<!--?php
namespace WebbyTroops\Product\Block;

class ProductImage
{
    /**
     * @var \Magento\Catalog\Api\ProductRepositoryInterfaceFactory
     */
    protected $productRepositoryFactory;
   
    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @param \Magento\Catalog\Api\ProductRepositoryInterfaceFactory $productRepositoryFactory
     * @param \Magento\Store\Model\StoreManagerInterface $storemanager
     */
    public function __construct(
        \Magento\Catalog\Api\ProductRepositoryInterfaceFactory $productRepositoryFactory,
        \Magento\Store\Model\StoreManagerInterface $storemanager
    ) {
        $this--->productRepositoryFactory = $productRepositoryFactory;
        $this-&gt;storeManager = $storemanager;
    }
    
    /**
     * @return string
     */
    public function getProductImageUrl()
    {
         $store = $this-&gt;storeManager-&gt;getStore();
         $productId = 1;
         $product = $this-&gt;productRepositoryFactory-&gt;create()-&gt;getById($productId);
        
         // This will give you all images with different size
         $product-&gt;getData('image');
         $product-&gt;getData('thumbnail');
         $product-&gt;getData('small_image');
         
         // This will provide image URL 
         $productImageUrl = $store-&gt;getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'catalog/product' . $product-&gt;getImage(); 
         return $productImageUrl;        
    }

    /**
     * Fetch all product images
     */
    public function getAllImages()
    {
        $store = $this-&gt;storeManager-&gt;getStore();
        $productId = 1;
        $product = $this-&gt;productRepositoryFactory-&gt;create()-&gt;getById($productId);
        $images = $product-&gt;getMediaGalleryEntries();
        $allImages = [];
        foreach ($images as $image) {
             if ($image-&gt;getMediaType() == 'image') {
                 $allImages[] = $store-&gt;getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'catalog/product' . $image-&gt;getFile();
             }
        }
        return $allImages;
    }
}

If you follow the steps as defined above, you will be able to get the product image and URL. If you face any issue, please comment below. Happy Coding!

Categories

Download The Free E-book & Launch Your Brand Strategically

Download The Free E-book & Launch Your Brand Strategically

Share this post