Magento 2 – Display Product Base Image in .phtml Template File

magento-2.1magento2phtmltemplate

SOLVED (See my answer below)


How can I display product base image in .phtml template file?

$relatedProducts = $product->getProduct()
        ->getRelatedProductCollection()
        ->addAttributeToSelect(['price','name','image','status']);

Can I put addAttributeToSelect to use for this?

I found this in one other post, but it doesn't work (I put it in Block/Product.php and called it in view/frontend/templates/related_products.phtml , the getImage() part doesn't get added to URL):

public function getProductImageUrl()
{
    return $this->_storeManager->getStore()
        ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'catalog/product' . $this->getImage();
}

Best Answer

This worked for me:

public function getProductImageUrl($product)
{
    return $this->_image->init($product, 'product_base_image')->constrainOnly(FALSE)
                ->keepAspectRatio(TRUE)
                ->keepFrame(FALSE)
                ->getUrl();
}