Magento – Getting a custom attribute image

imagemagento2product-images

Magento 2 question here:

I've made a custom attribute (media type) with the name of 'bike_range_image', and tried googling and searching in the core and everything I could to get the image with a custom size and such, but can't find the right approach.

I can get it as text, but obviously that's not enough, so this won't cut it:

$productImage = $product->getCustomAttribute( 'bike_range_image' );

Now, some examples in themes that are out there suggest I do this:

$this->helper('Magento\Catalog\Helper\Image')->init($product, 'bike_range_image');

But this gives me an enormous Magento\Catalog\Helper\Image object that doesn't seem to have the right data. (I've got the right product if you're wondering).

Does anyone have some pointers for me?

Best Answer

I guess you want to do it in .phtml file. Try this way

<?php
$productImageAttr = $product->getCustomAttribute( 'bike_range_image' );
$productImage = $this->helper('Magento\Catalog\Helper\Image')
    ->init($product, 'bike_range_image')
    ->setImageFile($productImageAttr->getValue());
?>

and then in img tag

<img src="<?php echo $productImage->getUrl() ?>" alt="<?php echo $block->escapeHtml($product->getTitle()) ?>" />

The image size can be defined in xml file, for example view.xml

<media>
    <images module="Magento_Catalog">
        <image id="bike_range_image" type="thumbnail">
            <width>100</width>
            <height>100</height>
        </image>
    </images>
</media>
Related Topic