Magento – product image url not valid – magento 2.0.1

magento2object-managerproductproduct-images

I have created a widget. I am trying to show product image in widget. I have successfully got product name, product url and image url using object manager. But the Image is not loaded (404 – not found).

public function getCollection()
{
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
    $collection = $productCollection->create()->setPageSize(1)
        ->addAttributeToSelect('*')
        ->load();

    return $collection;
}

public function getPImage()
{
 $col=$this->getCollection();
 foreach ($col as $product)
 {
    echo $product->getImage();
 }  
}

getPImage() method returns string "/m/b/mb01-blue-0.jpg"

I use this string in img src

<img style="height:100%;width:100%;" src="<?php echo $this->getViewFileUrl('images/m/b/mb01-blue-0.jpg'); ?>" />

or without images prefix

<img style="height:100%;width:100%;" src="<?php echo $this->getViewFileUrl('/m/b/mb01-blue-0.jpg'); ?>" />

Yet the image not found, broken image URL path. LumaChange is my custom theme.

http://magentodev.gworks.mobi/magento2/pub/static/frontend/LumaChange/Color/en_US/m/b/mb01-blue-0.jpg

when I found specific product by search store, image url look like below(valid)

http://magentodev.gworks.mobi/magento2/pub/media/catalog/product/cache/1/small_image/240x300/beff4985b56e3afdbeabfc89641a4582/m/b/mb01-blue-0.jpg

Page widget div tag looks like below

easy for your reference

Any suggestion to overcome this issue?

Best Answer

try:

define image size in app\design\frontend\MyPackage\mytheme\etc\view.xml as

<image id="my_widget_image_size" type="small_image">
    <width>240</width>
    <height>360</height>
</image>

then your function:

public function getPImage()
    {
     $col=$this->getCollection();
     $image = 'my_widget_image_size';
     foreach ($col as $product)
     {
        $productImage = $block->getImage($product, $image);
        echo $productImage ->toHtml();
     }  
    }

This will give you the entire image HTML. So don't put this inside img src.

Update: Get image url:

If above method did not work for you try this one.

public function getPImage()
        {
         $col=$this->getCollection();
         $image = 'my_widget_image_size';
         foreach ($col as $product)
         {
            $productImage = $block->getImage($product, $image);
            $_imagehelper = $this->helper('Magento\Catalog\Helper\Image');
            $productImage = $_imagehelper->init($product, $image)->constrainOnly(FALSE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->resize(400)->getUrl();
            echo $productImage;
         }  
        }
Related Topic