In this article, you going to see discussion regarding Magento 2 Get Product Image Url in phtml in a detail and step by step.
If you are looking for this topic then you are at right place.
Let’s start with the topic of Magento 2 Get Product Image Url in phtml.
It is very easy to get the product image Url for the product.
In case of Magento 2, each and every associated catalog product is with three images.
Images are small, Base and Thumbnail images.
During customization and development process many time requires product image Url.
The image Url is Mainly required in case of related, best seller or featured product.
So to get image url use the class file called as ProductRepositoryInterface file and Helper Image
file.
Use the below code from which you can understand easily.
<?php
public function __construct(
\Magento\Catalog\Helper\Image $imageHelper,
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository
) {
$this->imageHelper = $imageHelper;
$this->productRepository = $productRepository;
}
/**
* @param int $id
* @return string
*/
public function getItemImage($productId)
{
try {
$_product = $this->productRepository->getById($productId);
} catch (NoSuchEntityException $e) {
return 'Required product not found';
}
$image_url = $this->imageHelper->init($_product, 'product_base_image')->getUrl();
return $image_url;
}
Use the get Url method for getting image Url with passing type of images as a second parameter in above code snippet.
Below is the details of images.
Type | Width |
product_base_image | 265×265 |
product_page_image_large | 700×700 |
product_page_image_medium | 700×700 |
To get the image type as per your requirement use the given file path.
Below is the file path.
vendor/magento/theme-frontend-blank/etc/view.xml
Refer the below code snippet to get images Url by passing product id.
In the code you will see the method in product id is passed.
<?php
$productId = 14;
$productimgUrl = $this->getItemImage($productId);
?>
<div class="imagebox"><img src="<?php echo $productimgUrl; ?>" alt="product-image-url"/></div>
Magento 2 Get Base Url and Current Url – Complete Guide
Conclusion :
Use the above code for Magento Get Product Image Url in phtml
I hope you like this article and if you think that i have missing something, please comment below.