WebP is an image format specifically designed for the web.
JPEGs, PNGs and GIFs are still popular, but WebP is spreading rapidly. In fact, many websites and services (including WordPress and Google itself) are choosing it as their standard format.
So, how can
you create WebP images with PHP, if you have JPEG, PNG or GIF images? Let's find out.
You can use the imagewebp() function to create a WebP image with PHP.
This function takes three arguments:
An image resource.
Optionally, the path where to save the WebP file.
Optionally, the image quality value from 0 to 100.
First of all, you need an image resource. You need to use one of the PHP image* functions to get this resource. For example:
imagecreatefromjpeg() to create a resource from a JPEG file.
imagecreatefrompng() to create a resource from a PNG file.
imagecreatetruecolor() to create an empty image from scratch.
...and so on.
You can find the complete list of these functions here.
So, let's say that you have the image.jpg file, and you want to create a WebP image from it. The first step is to use imagecreatefromjpeg() to get the image resource:
Next, you can use imagewebp() to save the WebP image into a new file:
$dest = 'new_image.webp'; imagewebp($resource, $dest); And that's it: you have your new_image.webp image in the WebP
format.
Now, what if you want to automatically convert all your images into WebP in real-time, without having to save each file first? To do this, you need to create a special PHP
script that works as an automatic image converter.
So, let's say that you have this HTML code:
<div> <img src="myImage.jpg"> </div>
You want all images such as the one above automatically converted into the WebP format.
What you need to do is to replace
all the images with the PHP image converter script, passing the image name as a request parameter. Like this:
<div> <img src="webp.php?img=myImage.jpg"> </div>
The webp.php script does the following:
Reads the image file having the same name as the img request parameter.
How do you learn PHP fast, even if you have no experience? Here's how to go from zero to PHP developer in just 9 days. Take a look if you are a PHP beginner.
How do you make your PHP apps secure from attacks? Learn how to secure your code by using the right defense techniques (and stop worrying). See how to make your code secure.