magento2 get product collection with image code example

Example 1: magento2 get product collection

<?php
namespace Foungento\Theme\Block;
class Theme extends \Magento\Framework\View\Element\Template
{    
    protected $_productCollectionFactory;
        
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,        
        array $data = []
    )
    {    
        $this->_productCollectionFactory = $productCollectionFactory;    
        parent::__construct($context, $data);
    }
    
    public function getProductCollection()
    {
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->setPageSize(10); // fetching only 10 products
        return $collection;
    }
}
?>

/*Display product collection in phtml file
Print out the product collection in phtml file with the below code:*/

list.phtml
$productCollection = $block->getProductCollection();
foreach ($productCollection as $product) {
    print_r($product->getData());     
    echo "<br>";
}

Example 2: magento 2 get product image

use Magento\Framework\App\ObjectManager;
use Magento\Framework\View\Element\Template;
use Magento\Catalog\Model\Product;

class myClass extends Template
{	
	/**
	 * @param \Magento\Catalog\Model\Product $product
	 * @return \Magento\Catalog\Block\Product\Image
	 */
	public function getProductImage(Product $product){
		$objectManager =\Magento\Framework\App\ObjectManager::getInstance();
		/** @var \Magento\Catalog\Block\Product\ImageBuilder $imageBuilder */
		$imageBuilder = $objectManager->create(\Magento\Catalog\Block\Product\ImageBuilder::class);
		return $imageBuilder->create($product, 'category_page_grid');
	}
}

// in phtml use
<?=$block->getProductImage($product)?>

Example 3: magento 2 get product image

//todo get product object $product 

$objectManager =\Magento\Framework\App\ObjectManager::getInstance();
$helperImport = $objectManager->get('\Magento\Catalog\Helper\Image');

$imageUrl = $helperImport->init($product, 'product_page_image_small')
                ->setImageFile($product->getSmallImage()) // image,small_image,thumbnail
                ->resize(380)
                ->getUrl();
echo $imageUrl;

Tags:

Php Example