Images allow customers to pay more attention and when it comes to an eCommerce store, showing product images to customers gives then more confident and it is a must do activity for an online store. In today’s blog we will illustrate how you can fetch product image url in Magento 2.
<?php
namespace WebbyTroops\Product\Block;
class ProductImage
{
/**
*
* @var \Magento\Catalog\Api\ProductRepositoryInterfaceFactory
*/
protected $productRepositoryFactory;
/**
*
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;
/**
*
* @param \Magento\Authorization\Model\CompositeUserContext $userContext
* @param \Magento\Store\Model\StoreManagerInterface $storemanager
*/
public function __construct(
\Magento\Catalog\Api\ProductRepositoryInterfaceFactory $productRepositoryFactory,
\Magento\Store\Model\StoreManagerInterface $storemanager
) {
$this->productRepositoryFactory = $productRepositoryFactory;
$this->storeManager = $storemanager
}
/**
*
* @return int
*/
public function getProductImageUrl()
{
$store = $this->storeManager->getStore();
$productId = 1;
$product = $this->productRepositoryFactory->create()->getById($productId);
// This will give you all images with different size
$product->getData('image');
$product->getData('thumbnail');
$product->getData('small_image');
// This will provide image URL
$productImageUrl = $store->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'catalog/product' .$product->getImage();
return $productImageUrl;
}
/**
* fetch all Product images
*/
public function getAllImages()
{
$productId = 1;
$product = $this->productRepository->create()->getById($productId);
$images = $product->getMediaGalleryEntries();
$allImages = [];
foreach ($images as $image) {
if($image->getMediaType() == 'image') {
$allImages[] = $store->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'catalog/product' .$image->getFile();
}
}
return $allImages;
}
}
If you follow steps as defined above you will be able to get product image and url. If you face any issue please comment below. Happy Coding !!
Leave A Comment