2

I want to resized image of subcategory. for that, I added this code in .phtml file.I'm getting wrong path for image

<?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 
        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

1
  • Bhakti, Please check my updated ans in detailed way. Commented Feb 1, 2019 at 12:34

4 Answers 4

3

Create resize image by passing image URL

create Block file app\code\Ketan\Resize\Helper\Image.php

pass url and dimension

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */


    

namespace Ketan\Resize\Helper;

use Magento\Framework\Filesystem;
use Magento\Framework\Url;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Filesystem\DirectoryList;

class Image extends \Magento\Framework\App\Helper\AbstractHelper {
    protected $scopeConfig;
    protected $storeManager;
    protected $messageManager;
    protected $_response;
    protected $_resourceConfig;
    protected $_responseFactory;
    protected $_url;
    protected $_filesystem;
    protected $_directory;
    protected $_imageFactory;
    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\Message\ManagerInterface $messageManager,
        \Magento\Framework\App\ResponseInterface $response,
        \Magento\Framework\App\Config\Storage\WriterInterface $resourceConfig,
        \Magento\Framework\App\ResponseFactory $responseFactory,
        \Magento\Framework\UrlInterface $url,
        \Magento\Framework\Filesystem $filesystem,
        \Magento\Framework\Image\AdapterFactory $imageFactory
    )
    {
        $this->scopeConfig = $scopeConfig;
        $this->_storeManager=$storeManager;
        $this->messageManager=$messageManager;
        $this->_response=$response;
        $this->_resourceConfig=$resourceConfig;
         $this->_responseFactory = $responseFactory;
        $this->_url = $url;
        $this->_filesystem = $filesystem;
        $this->_directory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
        $this->_imageFactory = $imageFactory;
    }
    public function imageResize(
    $src,
    $width=35,
    $height=35,
    $dir='resize/'
    ){
        if (!@getimagesize($src)) {
            $src = $this->_storeManager->getStore()->getBaseUrl().'pub/media/catalog/product/placeholder/'.$this->scopeConfig->getValue('catalog/placeholder/small_image_placeholder',\Magento\Store\Model\ScopeInterface::SCOPE_STORE);
        }
        $absPath = $src;
        $imageResized = $this->_filesystem
        ->getDirectoryRead(DirectoryList::MEDIA)
        ->getAbsolutePath($dir).
        $this->getNewDirectoryImage($src);
        $imageResize = $this->_imageFactory->create();
        $imageResize->open($absPath);
        $imageResize->backgroundColor([255, 255, 255]);
        $imageResize->constrainOnly(TRUE);
        $imageResize->keepTransparency(TRUE);
        $imageResize->keepFrame(true);
        $imageResize->keepAspectRatio(true);
        $imageResize->resize($width,$height);
        $dest = $imageResized ;
        $imageResize->save($dest);
        $resizedURL= $this->_storeManager->getStore()
        ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA).
        $dir.$this->getNewDirectoryImage($src);
        return $resizedURL;
    }
    public function getNewDirectoryImage($src){
        $segments = array_reverse(explode('/',$src));
        $first_dir = substr($segments[0],0,1);
        $second_dir = substr($segments[0],1,1);
        return 'cache/'.$first_dir.'/'.$second_dir.'/'.$segments[0];
    }
}

In your phtml file

<?php foreach ($subcats as $subcat) { 
$_imgUrl = $subcat->getImageUrl(); ?>

<img src="<?php echo $this->helper('Ketan\Resize\Helper\Image')->imageResize($_imgUrl,'256','128','subtcat/'); ?>">

<?php } ?>
4
  • getting @Error filtering template: Warning: getimagesize(192.168.1.122/als2/pub/media/catalog/product/placeholder): failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found in D:\xampp\htdocs\als2\vendor\magento\framework\Image\Adapter\AbstractAdapter.php on line 304 Commented Feb 1, 2019 at 10:57
  • upload place holder image in admin small_image_placeholder prntscr.com/mf6jlv f there is no image it will take from there Commented Feb 1, 2019 at 11:02
  • I got resized img of placeholder but I want subcategory image Commented Feb 1, 2019 at 11:24
  • be sure are you passing category image url in $_imgUrl otherwise it will take place holder image Commented Feb 1, 2019 at 11:26
1

Please try this code for resized any images.

Using $objectManager :

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$directory = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList');
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$fileSystem = $objectManager->get('Magento\Framework\Filesystem');

$absolutePath = $objectManager->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::ROOT)->getAbsolutePath('pub/media/').$subcat->getUrl();
$imageResized = $objectManager->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath('resized/'.$width.'/').$subcat->getUrl();         

//create image factory...
$imageResize = $objectManager->create('\Magento\Framework\Image\AdapterFactory');       
$imageResize->open($absolutePath);
$imageResize->constrainOnly(TRUE);         
$imageResize->keepTransparency(TRUE);         
$imageResize->keepFrame(FALSE);         
$imageResize->keepAspectRatio(TRUE);         
$imageResize->resize($width,$height);  
//destination folder                
$destination = $imageResized;    
//save image      
$imageResize->save($destination);         

$resizedURL = $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA).'resized/'.$width.'/'.$image;

echo $resizedURL;

Using Helper :

<?php
namespace Vendor\Module\Helper;

use Magento\Store\Model\StoreManagerInterface;

class Imageresize extends \Magento\Framework\App\Helper\AbstractHelper
{    
    protected $_filesystem ;
    protected $_imageFactory;
    protected $_storeManager;
    protected $_objectManager;

    public function __construct(            
        \Magento\Framework\Filesystem $filesystem,         
        \Magento\Framework\ObjectManagerInterface $objectManager,
        StoreManagerInterface $storeManager,
        \Magento\Framework\Image\AdapterFactory $imageFactory         
        ) {         
        $this->_filesystem = $filesystem;               
        $this->_imageFactory = $imageFactory;        
        $this->_objectManager = $objectManager;
        $this->_storeManager = $storeManager; 
        }

    // pass imagename, width and height
    public function resize($image, $width = null, $height = null)
    {
        $absolutePath = $this->_filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::ROOT)->getAbsolutePath('pub/media/').$image;

        $imageResized = $this->_filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath('resized/'.$width.'/').$image;         
        //create image factory...
        $imageResize = $this->_imageFactory->create();         
        $imageResize->open($absolutePath);
        $imageResize->constrainOnly(TRUE);         
        $imageResize->keepTransparency(TRUE);         
        $imageResize->keepFrame(FALSE);         
        $imageResize->keepAspectRatio(TRUE);         
        $imageResize->resize($width,$height);  
        //destination folder                
        $destination = $imageResized;    
        //save image      
        $imageResize->save($destination);         

        $resizedURL = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA).'resized/'.$width.'/'.$image;

        return $resizedURL;
    } 
}
?>

And then add following code in your .phtml

<?php $imgResized = $this->helper('Vendor\Module\Helper\Imageresize')->resize($subcaturl,277,180); ?>
 <a href="<?php echo $br['link']; ?>"><img src="<?php echo $imgResized; ?>" /></a>

Please check and let me know if any issue.

0

Use below code to resize product and any custom image

Vendor\Module\Block\BlockName.php

<?php
namespace Vendor\Module\Block;
use Magento\Framework\App\Filesystem\DirectoryList;

class BlockName extends \Magento\Framework\View\Element\Template
{
    //upload image at -> /pub/media/directory/folderName/
    const DIRECTORY = 'directory/folderName';

    public function __construct(
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        \Magento\Catalog\Helper\Image $productImageHelper,
        \Magento\Framework\Filesystem $filesystem,
        \Magento\Framework\Image\AdapterFactory $imageFactory,
        \Magento\Backend\Block\Template\Context $context,
        array $data = []
    )
    {
        $this->storeManager = $storeManager;
        $this->productFactory = $productFactory;
        $this->_productImageHelper = $productImageHelper;
        $this->_mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
        $this->_imageFactory = $imageFactory;
        parent::__construct($context, $data);
    }

    // to resize product image
    public function getImageUrl($product)
    {
        $width = 600;
        $height = 600;
        return $this->resizeProductImage($product, $width, $height,$product->getImage());
    }

    public function getProduct($sku)
    {
        $product = $this->productFactory->create();
        return $product->loadByAttribute('sku', $sku);
    }

    public function resizeProductImage($product, $width, $height = null, $image = '')
    {
       return $this->_productImageHelper->init($product, 'product_base_image')
                ->setImageFile($image)
                ->resize($width, $height)->getUrl();
    }

    //for custom image -> upload image at -> /pub/media/directory/folderName/ -> path declared at variable DIRECTORY 
    public function resizeCustomImage($image, $width = null, $height = null)
    {
        $mediaFolder = self::DIRECTORY;
        $path = $mediaFolder . '/cache';
        if ($width !== null) {
            $path .= '/' . $width . 'x';
            if ($height !== null) {
                $path .= $height ;
            }
        }
        $absolutePath = $this->_mediaDirectory->getAbsolutePath($mediaFolder) . $image;
        $imageResized = $this->_mediaDirectory->getAbsolutePath($path) . $image;
        if (!file_exists($imageResized)) {
            $imageFactory = $this->_imageFactory->create();
            $imageFactory->open($absolutePath);
            $imageFactory->constrainOnly(true);
            $imageFactory->keepTransparency(true);
            $imageFactory->keepFrame(true);
            $imageFactory->keepAspectRatio(true);
            $imageFactory->resize($width, $height);
            $imageFactory->save($imageResized);
        }
        return $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . $path . $image;
    }
}
IN PHTML
For Product:
<img src='<?= $block->resizeProductImage($product, 700, 700, $product->getImage()); ?>'>

For Custom Image:
Base Dir -> /pub/media/directory/folderName/yourImage.png
<img src='<?= $block->resizeCustomImage('/yourImage.png', 700, 700); ?>'>
-1

I have written code for resizing any products images in Magento 2 according to your desired width and height. I will describe how to resize images In Magento2, Update product image in Magento2, Remove white frame in Magento 2, change product image dimensions Magento 2 such as needing to resize a custom image and display it on the site in special sized areas.

For Magento 2, you can use the following code to resize your images in Magento 2

Step 1: You need to create helper class file Image.php at Vender\Module\Helper\Image.php and the past below code.

< ?php
namespace Vender\Module\Helper;
use Magento\Framework\Filesystem;
use Magento\Framework\Url;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Filesystem\DirectoryList;
class Image extends \Magento\Framework\App\Helper\AbstractHelper {
    protected $scopeConfig;
    protected $storeManager;
    protected $messageManager;
    protected $_response;
    protected $_resourceConfig;
    protected $_responseFactory;
    protected $_url;
    protected $_filesystem;
    protected $_directory;
    protected $_imageFactory;
    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\Message\ManagerInterface $messageManager,
        \Magento\Framework\App\ResponseInterface $response,
        \Magento\Framework\App\Config\Storage\WriterInterface $resourceConfig,
        \Magento\Framework\App\ResponseFactory $responseFactory,
        \Magento\Framework\UrlInterface $url,
        \Magento\Framework\Filesystem $filesystem,
        \Magento\Framework\Image\AdapterFactory $imageFactory
    )
    {
        $this->scopeConfig = $scopeConfig;
        $this->_storeManager=$storeManager;
        $this->messageManager=$messageManager;
        $this->_response=$response;
        $this->_resourceConfig=$resourceConfig;
         $this->_responseFactory = $responseFactory;
        $this->_url = $url;
        $this->_filesystem = $filesystem;
        $this->_directory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
        $this->_imageFactory = $imageFactory;
    }
    public function imageResize(
    $src,
    $width=35,
    $height=35,
    $dir='resized/'
    ){
        $absPath = $this->_filesystem
        ->getDirectoryRead(DirectoryList::MEDIA)
        ->getAbsolutePath().$src;
        $imageResized = $this->_filesystem
        ->getDirectoryRead(DirectoryList::MEDIA)
        ->getAbsolutePath($dir).
        $this->getNewDirectoryImage($src);
        $imageResize = $this->_imageFactory->create(); 
        $imageResize->open($absPath);
        $imageResize->backgroundColor([255, 255, 255]);
        $imageResize->constrainOnly(TRUE);
        $imageResize->keepTransparency(TRUE);
        $imageResize->keepFrame(true);
        $imageResize->keepAspectRatio(true);
        $imageResize->resize($width,$height);
        $dest = $imageResized ;
        $imageResize->save($dest);
        $resizedURL= $this->_storeManager->getStore()
        ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA).
        $dir.$this->getNewDirectoryImage($src);
        return $resizedURL;
    }
    public function getNewDirectoryImage($src){
        $segments = array_reverse(explode('/',$src));
        $first_dir = substr($segments[0],0,1);
        $second_dir = substr($segments[0],1,1);
        return 'cache/'.$first_dir.'/'.$second_dir.'/'.$segments[0];
    }
}

Step 2: Using below code you can call above imageResize() method from any class, block or template.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$imgpath = $objectManager->create('Vender\Module\Helper\Image')->imageResize('IMAGE_PATH','50','50','YOUR_DIR_NAME/');

Now I am going to explain the methods I have used 1. getDirectoryRead() 2. getAbsolutePath() 3. backgroundColor() 4. constrainOnly() 5. keepTransparency() 6. keepFrame() 7. keepAspectRatio()

Magento 2 – Properly remove white image from frame

< ?php foreach ($this->getGalleryImages() as $_image): ?>

•  
             helper('catalog/image')->init($this->getProduct(), 'thumbnail', $_image->getFile())->resize(56); ?>" width="56" height="56" alt="< ?php echo $this->htmlEscape($_image->getLabel()) ?>" />

    < ?php endforeach; ?>

If you want resizing image in magento 2 and you want further information about this then read our blog : HOW TO RESIZE IMAGES IN MAGENTO 2?

1
  • Thank you, after solving the issue, I had written that blog :)) Commented Jul 30, 2019 at 9:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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