5

I want to get image url of product showing ,on product description page in phtml file. any help ?

Learner
  • 833
  • 3
  • 19
  • 42

3 Answers3

23

Try this

$product = $block->getProduct();

$imageUrl = $this->helper('Magento\Catalog\Helper\Image')
                    ->init($product, 'product_base_image')
                    ->constrainOnly(true)
                    ->keepAspectRatio(true)
                    ->keepTransparency(true)
                    ->keepFrame(false)
                    ->resize(150, 150)->getUrl();
Dinesh Yadav
  • 6,447
  • 2
  • 23
  • 50
  • thank you working fine. can I ask a small thing ? I want to show that image on a button click on pdp page aswell. I which I file code this ? – Learner Jan 18 '18 at 09:27
4
use Magento\Catalog\Helper\Image;

/**
         * Catalog Image Helper
         *
         * @var Image
         */
        protected $imageHelper;
public function __construct(
        Image $imageHelper
    ) {
        $this->imageHelper = $imageHelper;
    }

private function getAllSizeImages(ModelProduct $product, $imageFile)
    {
        return [
            'large' => $this->imageHelper->init($product, 'product_page_image_large_no_frame')
                ->setImageFile($imageFile)
                ->getUrl(),
            'medium' => $this->imageHelper->init($product, 'product_page_image_medium_no_frame')
                ->setImageFile($imageFile)
                ->getUrl(),
            'small' => $this->imageHelper->init($product, 'product_page_image_small')
                ->setImageFile($imageFile)
                ->getUrl(),
        ];
    }
Birjitsinh Zala
  • 1,167
  • 6
  • 19
4

This worked for me

// Step 1:  In your custom or block class add a variable  $_image
protected $_image;

//  Step 2: Injecting a class ( Magento\Catalog\Helper\Image ) into constructor
public function __construct(
    Magento\Catalog\Helper\Image $_image
) {
    $this->_image = $_image;
}

//  Step 3: Create a custom function
public function getProductImageUrl($product)
{
    return $this->_image->init($product, 'product_base_image')->constrainOnly(FALSE)
        ->keepAspectRatio(TRUE)
        ->keepFrame(FALSE)
        ->getUrl();
} 

and at last in your respective custom phtml call the getProductImageUrl method in that pass respective $poduct object.

Kanhaiya lal
  • 1,548
  • 12
  • 24
Asheem Patro
  • 1,070
  • 15
  • 28