Magento2 Product – How to Get Image and URL

event-observermagento2productproduct-images

This is my observer:

public function execute(\Magento\Framework\Event\Observer $observer)
{
    $orderIds = $observer->getEvent()->getOrderIds();
    $order = $this->_orderRepositoryInterface->get($orderIds[0]);
    $items =$order->getAllVisibleItems();
    $productQuantity = array();
    $productPrice = array();
    $productName = array();
    $productIds = array();
    foreach($items as $item) {
        $productIds[]= $item->getProductId();
        $productName[]= $item->getSku(); 
        $productPrice[] = $item->getPrice();
        $productQuantity[]= floor($item->getQtyOrdered());
    }
}

How can I get the product image and product URL from the item?

Best Answer

This way may not the best way to get a product image.

Inject \Magento\Catalog\Api\ProductRepositoryInterfaceFactory in the constructor.

protected $_productRepositoryFactory;

public function __construct(
 \Magento\Catalog\Api\ProductRepositoryInterfaceFactory $productRepositoryFactory
) {            
    $this->_productRepositoryFactory = $productRepositoryFactory;
}

We can get the image:

$product = $this->_productRepositoryFactory->create()
    ->getById($item->getProductId());
$product->getData('image');
$product->getData('thumbnail');
$product->getData('small_image');
Related Topic