How to convert jpg images to webp using php?

I am setting up a website of a real estate that imports the photos of an xml.

I wanted that when importing, it converted the 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 do this jpg to webp conversion, using php?

Thank you!

Author: Leandro Marzullo, 2019-05-14

2 answers

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, in 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 installing the imagick extension in PHP it will come with support for the ImageMagick webp already installed on your system. Confirm webp support at phpinfo()

Converting jpg to webp

$image = new Imagick('/caminho/para/seu/arquivo.jpg');
$image->setImageFormat('webp');
$image->writeImage('/caminho/para/seu/arquivo.webp');
 1
Author: Samuel Fontebasso, 2019-05-14 13:45:42

You can also use WebP.

In CENTOS 6.10 the following steps were required:

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

Have the gcc, make e 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 as command in php it was necessary:

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

In PHP exec :

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

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

Compiling with other platforms.

 0
Author: Oliveira, 2019-05-14 16:26:14