0

I need product image on custom phtml in magento 2.

Product is collection is a array not object.

I just want to product product_base_image , without loading product collection.

I tried

<?php

namespace Dev\Core\Helper;

use Magento\Catalog\Helper\Image;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\App\Helper\Context;

class Cart extends \Magento\Framework\Url\Helper\Data {

    public function __construct(
    Context $context, StoreManagerInterface $storeManger, ProductRepositoryInterface $productRepository, FormKey $formKey, Image $imageHelper
    ) {

        $this->imageHelper = $imageHelper;
        $this->productRepository = $productRepository;

        parent::__construct($context);
    }



    public function getItemImage($productId) {
        try {
            $_product = $this->productRepository->getById($productId);
        } catch (NoSuchEntityException $e) {
            return 'product not found';
        }
        $image_url = $this->imageHelper->init($_product, 'product_base_image')->getUrl();
        return $image_url;
    }

}

I m getting image with no issue. But i want to load image by product id without loading collection.

0

You can get the images directly, without loading the entire product, by using the following query:

<?php
namespace Dev\Core\Helper;

use Magento\Framework\App\Helper\Context;
use Magento\Framework\App\ResourceConnection;

class Cart extends \Magento\Framework\App\Helper\AbstractHelper
{
    private $_connection;

    public function __construct(
        Context $context,
        ResourceConnection $resourceConnection
    ) 
    {
        $this->_connection = $resourceConnection->getConnection();

        parent::__construct($context);
    }

    public function getItemImage($productId) 
    {
        $select = $connection->select()
            ->from('catalog_product_entity_media_gallery_value', '*')
            ->join(
                'catalog_product_entity_media_gallery',
                'catalog_product_entity_media_gallery_value.value_id=catalog_product_entity_media_gallery.value_id',
                array('image' => 'value')
            )
            ->where('entity_id = ?', $productId);

        try 
        {
            return $this->_connection->fetchAll($select);
        } catch (Exception $e) 
        {
            //log or handle exception
        }
    }
}

enter image description here

  • I need product image url. Not a product image name. – DEEPAK KUMAR Jan 2 '19 at 19:57
  • The above query returns everything you need including the file name and image name. You can find the file name in the value key of the returned results. See the screenshot I've attached to my answer. – Andrew Noble Jan 2 '19 at 20:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.