0

I want to get the product image in Magento 2.

$collection = $this->productCollectionFactory->create()
                ->addStoreFilter($this->_storeManager->getStore()->getId())
                ->addAttributeToSelect(array('name'))
                ->addAttributeToFilter(
                    [
                        ['attribute' => 'name', 'like' => '%' . $searchQuery . '%'],

                    ])
                ->addFieldToFilter('type_id', ['eq' => "sellabletype"]);

            foreach ($collection as $product) {
                $image_url = $this->image->init($product, 'product_page_image_small')->setImageFile($product->getSmallImage())->resize(200, 200)->getUrl();
                $searchCollection[] = ['name' => $product->getName(), 'url' => $product->getProductUrl(), 'image' => $image_url];
            }

But it return only Magento_Catalog/images/product/placeholder/thumbnail.jpg url

How to get product thumbnail image url.

| improve this question | | | | |
1

Your question was not clear. Do you want to get actual image instead of thumbnail? If not, please elaborate your requirement. If it is that, check it below.

Replace $product->getSmallImage() with $product->getImage() in the below line

From:

$image_url = $this->image->init($product, 'product_page_image_small')->setImageFile($product->getSmallImage())->resize(200, 200)->getUrl();

To:

$image_url = $this->image->init($product, 'product_page_image_small')->setImageFile($product->getImage())->resize(200, 200)->getUrl();

EDITED:

I'm not sure if it is a standard way or not. But try this

$imageUrl = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
$productUrl = $imageUrl.'catalog/product'.$product->getImage();
| improve this answer | | | | |
  • still it returns placeholder url not product thumbnail url – Mahi M Mar 28 '19 at 4:42
  • @ManoM Check the answer I have edited – Bhargava Rama Mar 28 '19 at 4:51
  • .$product->getImage(); returns empty. – Mahi M Mar 28 '19 at 5:14
  • Are you sure, does the product you are searching has images? Coz, $product->getImage() will work if the image exist – Bhargava Rama Mar 28 '19 at 6:40
0

you can get image url this way..

$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$imageHelper  = $_objectManager->get('\Magento\Catalog\Helper\Image');
$product = $_objectManager->create('Magento\Catalog\Model\Product')->load($product->getId());
<?php $image_url= $imageHelper->init($product, 'product_thumbnail_image')->setImageFile($product->getFile())->resize(200, 200)->getUrl(); ?>
| improve this answer | | | | |
  • its return only plcehoder thumbnail image – Mahi M Mar 28 '19 at 5:13

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.