Converting PNG images to WebP using PHP
Converting images from one format to another programmatically is sort of a common task. For example, you may want to convert all your PNG images to WebP format to save bandwidth and improve the performance of your application.
Luckily, it’s not that hard to do this in PHP. In this tutorial, I’ll show you how to convert PNG images to WebP images using PHP.
Installing PHP-GD
First of all, you need to install the PHP-GD extension. This extension is required to perform image manipulation in PHP. So, if you don’t have it installed, you have to install it first.
So, if you’re using Ubuntu and on PHP 8.1, you can install it like so.
$ sudo apt-get install php8.1-gd
The imagewebp
function
Once the PHP-GD extension is installed, we can leverage the imagewebp
function to convert PNG images to WebP images.
But before we get to that, we first need to make the target PNG image into a GD image resource using the imagecreatefrompng
function.
Here’s how we can do that.
$imagesDirectory = 'images/';
$imageName = 'image.png';
$gdImageInstance = imagecreatefrompng($imagesDirectory . $imageName);
Next, we can use this GD image instance to convert the PNG image to a WebP image using the imagewebp
function like so.
$webpImageName = 'image.webp';
$conversionSuccess = imagewebp(
$gdImageInstance,
$imagesDirectory . $webpImageName,
100
);
As you can tell, the imagewebp
function takes three arguments. The first argument is the GD image instance, the second argument is the path to the WebP image and the third argument is the quality of the image. The quality can be a value between 0 and 100.
This will create a WebP image in the same directory as the PNG image. The function will return true
on success or false
on failure. And that’s about it!
Lastly, we can destroy the GD image instance once the conversion is successful using the imagedestroy
function for cleaning up purposes like so.
if ($conversionSuccess) {
imagedestroy($gdImageInstance);
}
Putting it all together
Here’s the complete code that you can use to convert PNG images to WebP format.
$imagesDirectory = 'images/';
$imageName = 'image.png';
$webpImageName = 'image.webp';
$gdImageInstance = imagecreatefrompng($imagesDirectory . $imageName);
$conversionSuccess = imagewebp(
$gdImageInstance,
$imagesDirectory . $webpImageName,
100
);
if ($conversionSuccess) {
imagedestroy($gdImageInstance);
echo 'Conversion successful!';
}
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.