WebP image is one of best image format used on sites, it is smaller than other image formats, such as jpg and png. In this tutorial, we will introduce how to convert png, jpg to webp image, you can change your website images to webp by our this tutorial.
To convert other format images to webp, we shoud use php imagewebp() function:
imagewebp ( resource $image [, mixed $to = NULL [, int $quality = 80 ]] ) : bool
This function can save or ouput a webp image from other types of images.
Here we give a function to convert png to webp.
function convertImageToWebP($source, $destination, $quality=80) { $extension = pathinfo($source, PATHINFO_EXTENSION); if ($extension == 'jpeg' || $extension == 'jpg') $image = imagecreatefromjpeg($source); elseif ($extension == 'gif') $image = imagecreatefromgif($source); elseif ($extension == 'png') $image = imagecreatefrompng($source); return imagewebp($image, $destination, $quality); }
How does this function work?
Firstly, we get the format of source image by pathinfo().
$extension = pathinfo($source, PATHINFO_EXTENSION);
Create an image by image type
if ($extension == 'jpeg' || $extension == 'jpg') $image = imagecreatefromjpeg($source); elseif ($extension == 'gif') $image = imagecreatefromgif($source); elseif ($extension == 'png') $image = imagecreatefrompng($source);
Convert png, jpg to webp image
return imagewebp($image, $destination, $quality);
Then if you have converted webp image successfully, you can delete source image or not.
Moreover, if you plan to show webp image to browser using php, you can read this tutorial.
Understand WebP Image Mime Type and PHP Output it in Browser Directly – PHP Tutorial
Great tutorial. Thankyou
Hi, and if I dont want to save the file, just show?
use
header("Content-Type: image/webp");
or read tutorial Show WebP Image with PHPnot working. i tried using convertImageToWebP(‘pizza-hut.gif’, ‘om.webp’, 80); but its not working.
I have tested convertImageToWebp() with a gif image, it works. What are warnings or errors your php script output?
Tested and is working
Thankyou