Come ottenere l'immagine del prodotto e l'URL in Magento 2?


16

Questo è il mio osservatore:

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());
    }
}

Come posso ottenere l'immagine del prodotto e l'URL del prodotto dall'articolo?


Quale evento hai colto?
— Khoa TruongDinh,

checkout_onepage_controller_success_action
— Ramkishan Suthar

Risposte:


23

In questo modo potrebbe non essere il modo migliore per ottenere un'immagine del prodotto.

Iniettare \Magento\Catalog\Api\ProductRepositoryInterfaceFactorynel nostro costruttore.

protected $_productRepositoryFactory;

public function __construct(
        \Magento\Catalog\Api\ProductRepositoryInterfaceFactory $productRepositoryFactory
) {

    $this->_productRepositoryFactory = $productRepositoryFactory;
}

Possiamo ottenere l'immagine:

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

la tua risposta è giusta, ma cosa devo fare se ho più di un prodotto nel carrello come posso mostrare più di un'immagine del prodotto
— Ramkishan Suthar

ok ho capito @khoa. se ho più di un'immagine di produzione. grazie
— mille

Questo non funziona. Il valore restituito è una sorta di stringa come questa "/w/s/wsh10-orange_main.jpg"
— Hoang Trinh,

2
@piavgh è il percorso verso l'immagine:pub/media/catalog/product
— Khoa TruongDinh

1
quindi come posso usare /w/s/wsh10-orange_main.jpg nell'attributo <img src = "" /> in modo da poter caricare l'immagine reale
— Lachezar Raychev

18

Se vuoi l'URL di frontend pubblicato / cache di un'immagine per una vista dello store specifica (come ho fatto io), questo funziona per me:

/**
 * @var \Magento\Store\Model\App\Emulation
 */
protected $appEmulation;

/**
 * @var \Magento\Store\Model\StoreManagerInterface
 */
protected $storeManager;

/**
 * @var \Magento\Catalog\Api\ProductRepositoryInterfaceFactory
 */
protected $productRepositoryFactory;

/**
 * @var \Magento\Catalog\Helper\ImageFactory
 */
protected $imageHelperFactory;

/**
 * @param \Magento\Store\Model\StoreManagerInterface $storeManager
 * @param \Magento\Store\Model\App\Emulation $appEmulation
 * @param \Magento\Catalog\Api\ProductRepositoryInterfaceFactory $productRepositoryFactory
 * @param \Magento\Catalog\Helper\ImageFactory $helperFactory
 */
public function __construct(
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    \Magento\Store\Model\App\Emulation $appEmulation,
    \Magento\Catalog\Api\ProductRepositoryInterfaceFactory $productRepositoryFactory,
    \Magento\Catalog\Helper\ImageFactory $imageHelperFactory
)
{
    $this->storeManager = $storeManager;
    $this->appEmulation = $appEmulation;
    $this->productRepositoryFactory = $productRepositoryFactory;
    $this->imageHelperFactory = $imageHelperFactory;
}

Quindi, ovunque sia necessario ottenere l'URL del frontend dell'immagine:

$sku = "my-sku";
// get the store ID from somewhere (maybe a specific store?)
$storeId = $this->storeManager->getStore()->getId();
// emulate the frontend environment
$this->appEmulation->startEnvironmentEmulation($storeId, \Magento\Framework\App\Area::AREA_FRONTEND, true);
// load the product however you want
$product = $this->productRepositoryFactory->create()->get($sku);
// now the image helper will get the correct URL with the frontend environment emulated
$imageUrl = $this->imageHelperFactory->create()
  ->init($product, 'product_thumbnail_image')->getUrl();
// end emulation
$this->appEmulation->stopEnvironmentEmulation();

È possibile selezionare altri tipi di immagini oltre a product_thumbnail_image: vedere magento/theme-frontend-luma/etc/view.xmlun elenco di immagini di prodotti disponibili o crearne uno proprio in un view.xmlfile.


1
WTF? che è solo malato: D
— Lachezar Raychev,

Ho appena provato questa soluzione e non visualizzo alcun errore, anche se l'URL restituito non esiste e la stringa è vuota. Ho provato con 'product_base_image', 'product_small_image' e 'product_thumbnail_image', nessuno dei quali funziona. Potete consigliarmi per favore? Oppure esiste un modo efficace per farlo utilizzando l'archivio prodotti? Come sto già caricando altrove nel mio blocco.
— Joshua Flood,

11

Se devi restituire un URL del prodotto, dovrebbe apparire così:

//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;

6

È così che ho fatto. è abbastanza efficiente e pulito:

1) Innanzitutto, è necessario iniettare le seguenti classi:

protected $_storeManager;
protected $_appEmulation;
protected $_blockFactory;

public function __construct(
    ...
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    \Magento\Framework\View\Element\BlockFactory $blockFactory,
    \Magento\Store\Model\App\Emulation $appEmulation)
{
    $this->_storeManager = $storeManager;
    $this->_blockFactory = $blockFactory;
    $this->_appEmulation = $appEmulation;
}

2) Quindi, crea un metodo getImageUrl con il codice seguente:

protected function getImageUrl($product, string $imageType = '')
{
    $storeId = $this->_storeManager->getStore()->getId();

    $this->_appEmulation->startEnvironmentEmulation($storeId, \Magento\Framework\App\Area::AREA_FRONTEND, true);

    $imageBlock =  $this->_blockFactory->createBlock('Magento\Catalog\Block\Product\ListProduct');
    $productImage = $imageBlock->getImage($product, $imageType);
    $imageUrl = $productImage->getImageUrl();

    $this->_appEmulation->stopEnvironmentEmulation();

    return $imageUrl;
}

Nota: Il codice "appEmulation" è necessario solo quando si fare questa chiamata dalla amministrazione o per un API . Altrimenti, visualizzerai l'errore di seguito (o simile):

Unable to resolve the source file for 'webapi_rest/_view/en_AU/Magento_Catalog/images/product/placeholder/.jpg'

3) Chiama getImageUrl passando l'oggetto prodotto e il tipo di immagine che desideri (basato sul tuo file view.xml )

...
$smallImage = $this->getImageUrl($productObject, 'product_page_image_small');
...

1

Per ottenere l'URL dell'immagine personalizzata ho usato questo codice. Quindi se l'immagine non esce caricherà l'immagine del tema predefinito.

$product = $block->getProduct();

$productImageAttr = $product->getCustomAttribute('product_banner_image');

if ($productImageAttr && $productImageAttr->getValue() != 'no_selection') {

    $productImage = $this->helper('Magento\Catalog\Helper\Image')
    ->init($product, 'product_banner_image')
    ->setImageFile($productImageAttr->getValue());

    $imageUrl = $productImage->getUrl();

} else {

    $imageUrl = $this->getViewFileUrl('images/cat-img1.jpg'); // Theme/web/images

}
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.