How to Convert PNG to WEBP with PHP

Hello there, this post will help you understand how some of WordPress image conversion plugins work behind the scenes. This is very simple straight forward process using php image manipulation library GD, which is a default library on almost every server with PHP.

GD can do a lot of things like image creation, editing, cropping, and etc. This post will only focus on converting png images to webp, which is a next generation of image for format as per Google page speed test tool. If you do not know webp image format increases the page load.

Let’s dive in right away, so here is the folder structure on my Windows 10 system, I am using xampp package for PHP & MySQL development environment setup.

This is my initial folder structure in htdocs folder

Here is the php code that converts png images into webp format in the same folder.

The first foreach loop uses glob() method to read each png image from the folder, imagecreatefrompng() method reads and verifies the png format and imagewebp() method converts png into webp format with 100% image quality.

The second foreach loop reads all the webp images and prints on the webpage.

<?php 

// convert png to webp
foreach (glob('img/*.png') as $file) {
	$im = imagecreatefrompng($file);
	imagewebp($im, "$file".'.webp', 100);
	
}

// echo webp images on the webpage

foreach (glob('img/*.webp') as $webp) {
	echo "<img src='".$webp."' />";

}


Folder structure after converting png images to webp format.

png to webp

Suggestion: I should have removed png from from webp images but this is just experiment and I can do this in refactoring stage.

Download PHP 7 eBook For Free

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.