Magento 2 custom image resize

Today we talk about how to resize image in custom module. So let start talk about it with some background classes that are use to resize the image. In framework we use classes of Filesystem and Image\AdapterFactory. So here we go First we create the method resize in your block or you can create method in helper. In my example i am creating in my block.

   protected $_filesystem ;
   protected $_imageFactory;
   public function __construct(            
        \Magento\Framework\Filesystem $filesystem,        
        \Magento\Framework\Image\AdapterFactory $imageFactory        
        ) {        
        $this->_filesystem = $filesystem;              
        $this->_imageFactory = $imageFactory;        
        }

    // pass image Name, width and height
    public function resize($image, $width = null, $height = null)
    {
        $absolutePath = $this->_filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath('helloworld/images/').$image; //complete path of 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;
     }

Now we call our block method in our phtml.

$block->resize('test.jpg',500,400);

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

One thought on “Magento 2 custom image resize

  1. When I include this section to my constructor I get a 500 error in Magento 2.2.6. Any ideas? :

    protected $_filesystem ;
    protected $_imageFactory;
    public function __construct(
    \Magento\Framework\Filesystem $filesystem,
    \Magento\Framework\Image\AdapterFactory $imageFactory
    ) {
    $this->_filesystem = $filesystem;
    $this->_imageFactory = $imageFactory;
    }

Leave a Reply