1

how to display small images of product collection data?

Magento 2.0

3
  • could you add more detail about your question, what you are trying to do and what have you done so far ? Sep 11, 2018 at 5:59
  • I want to display small images on product view page @Naveed Sep 11, 2018 at 6:54
  • I have product collection data but I have not idea how to display product images. @Naveed Sep 11, 2018 at 6:55

1 Answer 1

1

Get collection of products in Block

<?php
namespace Vendor\Module\Block;
use Magento\Framework\View\Element\Template;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Catalog\Helper\Image;
use Magento\Catalog\Model\ProductRepository;

class Products extends Template
{    
   protected $_productCollectionFactory;
   protected $_productImageHelper;
   protected $_productRepository;

   public function __construct(
        Context $context,        
        CollectionFactory $productCollectionFactory,
        Image $productImageHelper,
        ProductRepository $productRepository,
    )
    {    
        $this->_productCollectionFactory = $productCollectionFactory;
        $this->_productImageHelper = $productImageHelper;
        $this->_productRepository = $productRepository;
        parent::__construct($context);
    }
    public function getProductBySku($sku)
    {
        return $this->_productRepository->get($sku);
    }

     public function resizeImage($product,$imageId, $width, $height = null)
        {
            $_product = $this->getProductBySku($product->getSku());
            $resizedImage = $this->_productImageHelper
                               ->init($_product, $imageId)
                               ->constrainOnly(TRUE)
                               ->keepAspectRatio(TRUE)
                               ->keepTransparency(TRUE)
                               ->keepFrame(FALSE)
                               ->resize($width, $height);
            return $resizedImage;
    }

    public function getProductCollection(){

        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
        $collection->addAttributeToSort('name', 'ASC');
        return $collection;
    }
}

Call collection in phtml file and display images like below

<?php $productCollection = $block->getProductCollection(); ?>

<?php foreach ($productCollection as $_product) { 

$resizedImageUrl = $block->resizeImage($_product, 'product_base_image', 80, 80)->getUrl();  ?>
echo "<img src=".$resizedImageUrl."/>";

}
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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