Skip to main content
1 of 5
Bhakti Thakkar
  • 1.3k
  • 15
  • 35

How to resize sub category Image in Magento 2?

I want a resized image of subcategory on the home page. for that, I added this code in phtml file.

<?php
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $catId = 3;  //Parent Category ID
    $subCategory = $objectManager->create('Magento\Catalog\Model\Category')->load($catId);
    $subCats = $subCategory->getChildrenCategories();
    $_helper = $this->helper('Magento\Catalog\Helper\Output');
    $_imagehelper = $this->helper('Magento\Catalog\Helper\Image');
    $count = 0;
?>
<div class="container homecat">
<div class="row">

    <?php
?>
    
    <?php
    
    foreach ($subCats as $subcat) {
        
        $_category = $objectManager->create('Magento\Catalog\Model\Category')->load($subcat->getId());
        $subcaturl = $subcat->getUrl();
        $_imgHtml = '';
        
        $subcaturl =  $_imagehelper->init($_category, 'image')->keepAspectRatio(TRUE)
                    ->constrainOnly(TRUE)
                    ->keepAspectRatio(TRUE)
                    ->keepTransparency(TRUE)
                    ->resize('256','128')
                    ->getUrl();

        echo $subcaturl ."<br/>";
        $_imgHtml = '<img src="' . $subcaturl . '" />';
        $_imgHtml = $_helper->categoryAttribute($_category, $_imgHtml, 'image');
        echo $_imgHtml;

         } ?>

</div>
</div>

I am getting

http://Hostname/als2/pub/static/version1549014696/frontend/Theme/Name/en_US/Magento_Catalog/images/product/placeholder/.jpg

Bhakti Thakkar
  • 1.3k
  • 15
  • 35