How to convert jpg images to webp using php?

Asked

Viewed 571 times

4

I’m setting up a real estate website that imports photos of an xml.

I wanted that when importing, it converted jpg to webp, but of the ones I found on the net, I could not make it work.

Does anyone know a good way to convert jpg to webp using php?

Thank you!

  • 1

    Leandro gives a look at the function imagewebp() of own PHP

2 answers

1

You can use Imagemagick with PHP for this task, but native webp support may not be ready.

To ensure this install the library libwebp-dev, on Ubuntu:

sudo apt install libwebp-dev

Compiling Imagemagick on Ubuntu 18.04

cd /tmp
mkdir imagemagick
cd imagemagick
wget https://www.imagemagick.org/download/ImageMagick.tar.gz
tar xvzf ImageMagick.tar.gz

sudo apt-get build-dep imagemagick
sudo apt-get install libwebp-dev devscripts
sudo apt-get install graphicsmagick-imagemagick-compat
apt-get source imagemagick
cd ImageMagick-*

./configure
make
sudo make install
sudo ldconfig /usr/local/lib

magick -version

Installing Imagick extension in PHP 7.2

sudo pecl install imagick

When you install the Imagick extension in PHP it will come with Imagemagick webp support already installed on your system. Confirm webp support on phpinfo()

Converting jpg for webp

$image = new Imagick('/caminho/para/seu/arquivo.jpg');
$image->setImageFormat('webp');
$image->writeImage('/caminho/para/seu/arquivo.webp');

0

Can also be used the Webp.

In the CENTOS 6.10 it took the following steps:

yum install gcc gcc-c++ kernel-devel    
yum install libjpeg-devel libpng-devel libtiff-devel libgif-devel

Have the gcc, make and automake

cd /opt        
wget https://storage.googleapis.com/downloads.webmproject.org/releases/webp/libwebp-1.0.2.tar.gz    
tar xvzf libwebp-1.0.2.tar.gz    
cd libwebp-1.0.2
./configure
make
sudo make install

The cwebp and dwebp , were made available in the directory /usr/local/bin/, to use command in php:

cd /usr/local/bin/
mv cwebp /usr/bin/
mv dwebp /usr/bin/

In the PHP was used the exec:

<?php
$imgName    =   "php.jpg";
$webPName   =   "php.webp";

if(file_exists($imgName)){
    exec("cwebp -q 80 $imgName -o $webPName");    
}

Compiling with other platforms.

  • 1

    I just wanted to suggest that you use escapeshellcmd and escapeshellarg. At least at least indicate that the $imgName and $webPName should not be manipulated by the end user, although this does not fix definitely. This may be obvious to some, but not to all future readers.

  • @Inkeliz, a totally valid suggestion, the idea was to suggest one more possibility to add with the contribution of Luke and Samuel.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.