Before we continue on how to convert jpg to webp, we need to enable PHP GD library. If you are using XAMPP on Windows, you can follow these instructions (I am using XAMPP 8.1):
- Open XAMPP Control Panel.
- Go to Apache module and click Config. Choose php.ini.
- Make sure there is
extension=php_gd
. - Restart Apache module.
If GD library is enabled, now we can go to the main code. Here is the code, this will convert all files within a folder to webp.
<?php
$path = 'C:\xampp\htdocs';
$files = array_diff(scandir($path), array('.', '..'));
foreach ($files as $key => $value) {
$file = $path.'/'.$value;
$filename = pathinfo($file, PATHINFO_FILENAME);
echo $filename."<br/>";
$jpg = imagecreatefromjpeg($file);
$w = imagesx($jpg);
$h = imagesy($jpg);
$webp = imagecreatetruecolor($w,$h);
imagecopy($webp,$jpg,0,0,0,0,$w,$h);
imagewebp($webp, $filename.'.webp', 30);
imagedestroy($jpg);
imagedestroy($webp);
}
?>
The code above is obtained from Stackoverflow’s answer (https://stackoverflow.com/a/64238458) with a few changes based on my needs.
Leave a Reply