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;
}
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);