Getting a Product Image URL in Magento 2

Getting a Product Image URL in Magento 2

Custom templates, feeds and emails often need a product image URL. Here is a direct way to get it in Magento 2.

Example

<?php
  $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
  $_product = $objectManager->get('Magento\Catalog\Model\Product')->load($_item->getProduct()->getId());

    $image = 'wishlist_thumbnail';
    $_imagehelper = $this->helper('Magento\Catalog\Helper\Image');
    $productImage = $_imagehelper->init($_product, $image)->constrainOnly(FALSE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->resize(200)->getUrl();
?>
<img src="<?php echo $productImage; ?>" alt="<?php echo $_product->getName() ?>" />

For resized or cached images that match your theme settings, use Magento\Catalog\Helper\Image with an image ID from your theme’s view.xml.

Stuck on something similar? Our Magento development team is happy to take a look.

Keep reading

Related articles

All articles

Need a hand?

Stuck on something similar?
We can fix it with you.

Send us the problem. A senior developer reads every message and replies within one working day.