:::: MENU ::::

Magento 2 custom image resize

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();        
        //destination folder                
        $destination = $imageResized ;    
        //save image      

        $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.

Author: Qaisar Satti
Category: Magento 2
Last Modified: December 15, 2017

So, what do you think ?