Magento 2: Get image url in template file

0
735

Magento 2 Getting Image URL for template files

Step 1: Put your image on Your Magento 2 Path: 

/app/design/frontend/<Vendor>/<theme>/web/images

Step 2: Use this code to call the image in phtml file

<?php echo $block->getViewFileUrl('images/demo.jpg'); ?>

Or images in

Vendor/theme/Vendor_Module/web/images or app/code/Vendor/Module/view/frontend/web/images/

<img src="<?php echo $this->getViewFileUrl('Vendor_Module::images/image.png'); ?>" />

Magento 2 Getting Image URL for CMS Blocks

Images in

Vendor/theme/Vendor_Module/web/images or app/code/Vendor/Module/view/frontend/web/images/

<img src="{{view url='Vendor_Module::images/image.png'}}"/>

or if images are in Vendor/theme/web/images/

<img src="{{view url='images/image.png'}}"/>

That is it, so next time you need to get that image in place.

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 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');
 ...