0

I can safely resize an image with jpg or png format like this :

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

public function resizeImage($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;
}

but when if i try to convert webp image, i always got an error like this:

Exception #0 (InvalidArgumentException): Unsupported image format. File: /var/www/Mage2/pub/media/banner/main.webp

2 Answers 2

1

you can look into this extension

Magento 2 module to add WebP support to Magento 2.

When <img> tags are found on the page, the corresponding JPG or PNG is converted into WebP and a corresponding <picture tag is used to replace the original <img> tag.

https://github.com/yireo/Yireo_Webp2

it is free, you can check how it works

0

Magento 2 does not support .webp images out of the box.

Your best bet is probably to use an extension for adding .webp images to your store. This not only saves you to deal with resizing .webp but also creating/uploading the .webp images in the first place.

You can have a look at our WebP Optimized Images Extension for Magento 2.

With this extension, there is no need for resizing or manually converting or uploading the .webp files. Images are converted to .webp following the same size as your original .jpg/.png images.

Conversion is done automatically, with configurable compression supporting 3 different conversion tools and on your own server with no need to use and pay any 3rd Party Service. This while being 100% compatible with Varnish / FPC as well as any Browser.

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.