magento2 get category image

magento2 get category image

Today we will learn about magento2 get category image in phtml file.

I have Used This code to get Category images in my code Please look at these.

I am using this module Myvendor/Mymodule.

Solution 1

File: app/code/Myvendor/Mymodule/Block/Home/Category.php

namespace Myvendor\Mymodule\Block\Home;

use Magento\Framework\View\Element\Template\Context;
use Magento\Catalog\ViewModel\Category\Image;

class Category extends \Magento\Framework\View\Element\Template
{
    public $image;
    public function __construct(
        Context $context,
        Image $image,        
        array $data = []
    ) {        
        $this->image = $image;       
        parent::__construct($context, $data);
    }

    public function getCategoryImageUrl(\Magento\Catalog\Model\Category $category)
    {
        return $this->image->getUrl($category, 'thumbnail_image');
                             OR   
        return $this->image->getUrl($category, 'image');
    }
}

phtml file : app/code/Myvendor/Mymodule/view/frontend/templates/home/home_category.phtml

Call getCategoryImageUrl funciton in phtml file

$categoryImg = $block->getCategoryImageUrl($category);

<img src="<?php echo $categoryImg  ?>"  />

Magento2 get category image

Solution 2

<?php
$categoryId = 2;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$category = $objectManager->create('Magento\Catalog\Model\Category')->load($categoryId);
$_outputhelper    = $this->helper('Magento\Catalog\Helper\Output');
$_imgHtml   = '';
if ($_imgUrl = $category->getImageUrl()) {
   $_imgHtml = '<img src="' . $_imgUrl . '" />';
   $_imgHtml = $_outputhelper->categoryAttribute($category, $_imgHtml, 'image');
    echo $_imgHtml;
}
?>

Hope the above code will save you time.

Related Post: Magento 2.4 Newsletter Using Ajax

Like us on Facebook and Linkedin for more updates.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top