Magento 2 – CollectionFactory Image, Thumbnail, Small_Image Issues

magento2product-collectionproduct-images

In my custom block, I get Product Collection use \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory, when I output one product in it, the image, thumbnail, small_image are the same url like below, a large image(1380px x 1340px) url:

[image] => /m/b/mb04-black-0.jpg
[small_image] => /m/b/mb04-black-0.jpg
[thumbnail] => /m/b/mb04-black-0.jpg

Did I do something wrong? How do I get the real small_image or thumbnail URL from product collection?

More question description

For example, in the default luma theme category, product list always get the image like below:

<img class="product-image-photo" src="http://local.com/pub/media/catalog/product/cache/small_image/240x300/beff4985b56e3afdbeabfc89641a4582/w/t/wt09-white_main.jpg" width="240" height="300" alt="Breathe-Easy Tank">

How can I get that?

My code example

Below is my code, I remove some function for simplicity.

<?php
namespace Vendor\Template\Block;

use Magento\Framework\View\Element\Template;
use Magento\Backend\Block\Template\Context;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;

class Product extends Template
{
    protected $_productCollectionFactory;

    public function __construct(
        Context $context,
        CollectionFactory $productCollectionFactory,
        array $data = []
    )
    {
        $this->_productCollectionFactory = $productCollectionFactory;
        parent::__construct($context, $data);
    }

    public function getProductCollection()
    {
        $skus = $this->getData('products_count');
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*')
            ->addAttributeToFilter(
                'sku', array('in' => $skus)
            );
        return $collection;
    }
}

Best Answer

Then you should use `\Magento\Catalog\Helper\Image ' resize the product image

$resizedImage = $this->_productImageHelper->init($product, 'product_small_image')
                                           ->constrainOnly(TRUE)
                                           ->keepAspectRatio(TRUE)
                                           ->keepTransparency(TRUE)
                                           ->keepFrame(FALSE)
                                           ->resize(200, 300);

Magento 2 resize category & product image

https://www.mageplaza.com/how-change-product-image-size-magento-2.html

Related Topic