Good images compliment product descriptions and simplify buying decisions. You might sometimes need to retrieve product image URLs while developing some features related to images, or you might need them while migrating to a new store.
This tutorial shows all the necessary logic to get the product image URL in Magento 2.
This article assumes you’ve registered necessary files such as etc/module.xml and registration.php.
How to Get Product Image URL in Magento 2
Use the following code to get the product image URL in Magento 2:
<?php
public function __construct(
MagentoCatalogHelperImage $imageHelper,
MagentoCatalogApiProductRepositoryInterface $productRepository
) {
$this->imageHelper = $imageHelper;
$this->productRepository = $productRepository;
}
/**
* @param int $id
* @return string
*/
public function getItemImage($productId)
{
try {
$_product = $this->productRepository->getById($productId);
} catch (NoSuchEntityException $e) {
return 'product not found';
}
$image_url = $this->imageHelper->init($_product, 'product_base_image')->getUrl();
return $image_url;
}
Here, we’ve called “product_base_images.” There are other product image types that you can use in the second argument above, such as “product_page_image_large,” “product_thumbnail_image,” and “product_page_image_medium.”
The properties of product images are stored in the “view.xml’ file. You can check out the “magento/theme-frontend-luma/etc/view.xml” file to see a list of available product images. You can also create a list in the “view.xml file.”
If you wish to get a product image URL of a specific product, use the following code in the “phtml” file:
<?php
$productId = 10;
$imgUrl = $this->getItemImage($productId);
?>
<div class="image-box"><img src="<?= $imgUrl; ?>" alt="product-image"/></div>