Magento Tutorials

How to Get Product Image URL in Magento 2

In some cases such as migrating your Magento site, you need to get the full URLs of your product images. This post will answer this question. This is one of the most efficient ways to do it.

First, you need to inject the following classes:

protected $_storeManager;
protected $_appEmulation;
protected $_blockFactory;

public function __construct(
 ...
 \Magento\Store\Model\StoreManagerInterface $storeManager,
 \Magento\Framework\View\Element\BlockFactory $blockFactory,
 \Magento\Store\Model\App\Emulation $appEmulation)
 {
 $this->_storeManager = $storeManager;
 $this->_blockFactory = $blockFactory;
 $this->_appEmulation = $appEmulation;
 }

Then, create a getImageUrl method with the following code:

protected function getImageUrl($product, string $imageType = '')
 {
 $storeId = $this->_storeManager->getStore()->getId();

$this->_appEmulation->startEnvironmentEmulation($storeId, \Magento\Framework\App\Area::AREA_FRONTEND, true);

$imageBlock = $this->_blockFactory->createBlock('Magento\Catalog\Block\Product\ListProduct');
 $productImage = $imageBlock->getImage(product, $imageType);
 $imageUrl = $productImage->getImageUrl();

$this->_appEmulation->stopEnvironmentEmulation();

return $imageUrl;
 }

Be noted to use only “appEmulation” code when you making this call from the admin or for an API. Otherwise, you will get the error below (or a similar one):

Unable to resolve the source file for 'webapi_rest/_view/en_AU/Magento_Catalog/images/product/placeholder/.jpg'

Finally, call the getImageUrl passing the product object and the type of image you want.

By default, the properties of product images are stored in the view.xml configuration file.

...
 $smallImage = $this->getImageUrl($productObject, 'product_page_image_small');
 ...

See more:
How to Resize Images in Magento 1 & 2
Upload Images for Configurable Swatches in Magento

Dom

A knowledge craver who always strive to be wiser everyday.