0

How to get product images of a specific category in magento2?

1 Answer 1

1

Following code might help you.

protected $_productCollectionFactory;
protected $_categoryFactory;
protected $_imageHelper;

public function __construct(
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
    \Magento\Catalog\Model\CategoryFactory $categoryFactory,
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\Catalog\Helper\Image $imageHelper
) {
    $this->_categoryFactory = $categoryFactory;
    $this->_productCollectionFactory = $productCollectionFactory;
    $this->__imageHelper = $imageHelper;
    parent::__construct($context);
}

public function getProductCollection()
{
    $categoryId = 'yourcategoryid';
    $category = $this->_categoryFactory->create()->load($categoryId);
    $collection = $this->_productCollectionFactory->create();
    $collection->addAttributeToSelect('*');
    $collection->addCategoryFilter($category);
    $collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
    $collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
    return $collection;
}

public function getImageUrl(){
    $collection = $this->getProductCollection();

    foreach ($collection as $product){

        // small image 
        echo $this->_imageHelper->init($product, 'product_page_image_small')->getUrl();

        // medium image 
        echo $this->_imageHelper->init($product, 'product_page_image_medium')->constrainOnly(true)->keepAspectRatio(true)->keepFrame(false)->getUrl();

        // large image 
        echo $this->_imageHelper->init($product, 'product_page_image_large')->constrainOnly(true)->keepAspectRatio(true)->keepFrame(false)->getUrl();


    }

}

PS: I haven't tested it but it should work as per my experience.

8
  • Thanks for the answer, how to load the images of category in phtml file May 12, 2018 at 10:20
  • iam getting only one category image of product May 12, 2018 at 13:10
  • create a function in block and load category and return image url using : $categoryId = 'yourcategoryid'; $category = $this->_categoryFactory->create()->load($categoryId); return $category->getImageUrl(); May 13, 2018 at 7:37
  • thanks for your reply, I will check it and get back to you May 13, 2018 at 7:46
  • Don't forget to accept the answer if it is working for you. Thanks. May 13, 2018 at 8:05

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.