Magento 2 get product images

Today we talk about how in Magento 2 get product images for example thumbnail images, base images and small images.You can get these image in custom collection or product page. First you have to inject the ImageBuilder class in you block. You can get product collection or load the single product or get product current information. So let start with example. There is default available image types.

$imageType = 'product_base_image';  //For getting the base image
$imageType = 'product_small_image';  //For getting the small image
$imageType = 'product_thumbnail_image';   //For getting the thumbnail image

Now we inject the ImageBuilder class in our block.

protected $_imageBuilder;

public function __construct(
       
        \Magento\Catalog\Block\Product\ImageBuilder $_imageBuilder
    ) {
   
       
        $this->_imageBuilder=$_imageBuilder;
            }


 public function getImage($product, $imageId, $attributes = [])
    {
        return $this->_imageBuilder->setProduct($product)
            ->setImageId($imageId)
            ->setAttributes($attributes)
            ->create();
    }

Get Image in phtml

 <?php  

$imageType = 'product_thumbnail_image';
$image = $block->getImage($_item, $imageType); ?>
 <img src="<?php echo $image->getImageUrl(); ?> " />

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

One thought on “Magento 2 get product images

Leave a Reply