How to get the product image in Magento 2
-
24-02-2021 - |
質問
I want to get the product image in Magento 2.
$collection = $this->productCollectionFactory->create()
->addStoreFilter($this->_storeManager->getStore()->getId())
->addAttributeToSelect(array('name'))
->addAttributeToFilter(
[
['attribute' => 'name', 'like' => '%' . $searchQuery . '%'],
])
->addFieldToFilter('type_id', ['eq' => "sellabletype"]);
foreach ($collection as $product) {
$image_url = $this->image->init($product, 'product_page_image_small')->setImageFile($product->getSmallImage())->resize(200, 200)->getUrl();
$searchCollection[] = ['name' => $product->getName(), 'url' => $product->getProductUrl(), 'image' => $image_url];
}
But it return only Magento_Catalog/images/product/placeholder/thumbnail.jpg url
How to get product thumbnail image url.
解決
Your question was not clear. Do you want to get actual image instead of thumbnail? If not, please elaborate your requirement. If it is that, check it below.
Replace $product->getSmallImage() with $product->getImage() in the below line
From:
$image_url = $this->image->init($product, 'product_page_image_small')->setImageFile($product->getSmallImage())->resize(200, 200)->getUrl();
To:
$image_url = $this->image->init($product, 'product_page_image_small')->setImageFile($product->getImage())->resize(200, 200)->getUrl();
EDITED:
I'm not sure if it is a standard way or not. But try this
$imageUrl = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
$productUrl = $imageUrl.'catalog/product'.$product->getImage();
他のヒント
you can get image url this way..
$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$imageHelper = $_objectManager->get('\Magento\Catalog\Helper\Image');
$product = $_objectManager->create('Magento\Catalog\Model\Product')->load($product->getId());
<?php $image_url= $imageHelper->init($product, 'product_thumbnail_image')->setImageFile($product->getFile())->resize(200, 200)->getUrl(); ?>
所属していません magento.stackexchange