Batch Convert Images to WebP Using PHP: A Complete Guide
In today’s web development, optimizing images is crucial for faster loading speeds and better performance. WebP is a modern image format developed by Google that provides superior compression compared to PNG and JPEG. In this guide, we’ll show you how to batch convert images (JPG, PNG) to WebP using PHP.
Why Use WebP?
- Smaller File Size – 25-34% smaller than JPEG/PNG with the same quality.
- Supports Transparency – Like PNG but more efficient.
- Faster Loading – Reduces bandwidth usage and improves SEO.
- Animation Support – Works like GIF but better compression.
PHP Script to Convert Images to WebP
PHP’s GD Library allows us to process images efficiently. Below is a simple script to convert all JPG/PNG images to WebP format in a directory.
Step 1: Enable GD Library
Make sure GD Library is enabled in your PHP setup. Run this command in CLI:
php -m | grep gd
If it’s not enabled, add the following line in php.ini and restart the server:
extension=gd
Step 2: PHP Script for Batch Conversion
$input_dir = "input_images"; // Folder with JPG/PNG images
$output_dir = "output_images"; // Folder for WebP images
if (!is_dir($output_dir)) {
mkdir($output_dir, 0777, true);
}
// Get all JPG/PNG images from input directory
$images = glob("$input_dir/*.{jpg,jpeg,png}", GLOB_BRACE);
foreach ($images as $image) {
$img_info = pathinfo($image);
$output_path = "$output_dir/{$img_info['filename']}.webp";
// Skip if WebP already exists
if (file_exists($output_path)) {
echo "Skipping: {$img_info['basename']} (already converted)\n";
continue;
}
// Load image
if (in_array($img_info['extension'], ['jpg', 'jpeg'])) {
$img = imagecreatefromjpeg($image);
} elseif ($img_info['extension'] === 'png') {
$img = imagecreatefrompng($image);
} else {
continue;
}
// Convert to WebP (Quality: 80)
imagewebp($img, $output_path, 80);
imagedestroy($img);
echo "Converted: {$img_info['basename']} -> {$img_info['filename']}.webp\n";
}
echo "✅ Batch conversion complete!";
Step 3: How to Use the Script?
- Create a folder named
input_images
and place all your JPG/PNG images inside it. - Save the PHP script in a file (e.g.,
convert.php
) and place it in the same directory asinput_images
. - Run the script using the command line or browser.
- Check the
output_images
folder for the converted WebP images.
Additional Enhancements
- Adjust Quality: Change the 80 value in imagewebp() to control compression.
- Convert GIF & BMP: Add imagecreatefromgif() or imagecreatefrombmp().
- Web Interface: Integrate with a web form to allow users to upload and convert images.
That’s it! You’ve successfully batch converted JPG/PNG images to WebP using PHP. Feel free to modify the script to suit your requirements and optimize images for your website.