2

I need to generate an email template with product image included in it, i need to check if the product image exist or not , if product image not exist i want to generate magento 2 default product image thumbnail with custom size, now i'm generating custom size product image with this:

$product = $objectManager->create('Magento\Catalog\Model\Product')->load($data['item_id']);
$imageHelper = $objectManager->get('\Magento\Catalog\Helper\Image');
$width = 150; $height = 150;
$imageUrl = $imageHelper->init($product,'product_page_image_small')->setImageFile($product->getFile())->resize($width,$height)->getUrl();
echo $imageUrl;

because the product doesn't have image it produce url like this:

http://test.com/pub/static/version1496373583/adminhtml/Magento/backend/en_US/Magento_Catalog/images/product/placeholder/.jpg
2

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

protected $_productRepositoryFactory;

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

    $this->_productRepositoryFactory = $productRepositoryFactory;
}

We can get the image as follows

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

$product->getData('image') will return empty value if product has no base image. So you can use that condition and if product has no base image then you can print placeholder image url.

  • @how to print the placeholder image url? – simple guy Jun 2 '17 at 6:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.