Serving Next-Gen Image Formats with PHP
If you're running a custom store or your own CMS, you don't need a media plugin to handle WebP for you. PHP ships with the GD library, and a small function can convert images to WebP the moment they're uploaded — no extra dependencies, no front-end JavaScript, and depending on the source images, often more than half the file size gone. This guide walks through the code for both JPEG and PNG, including the part most tutorials skip: keeping transparency intact.
Key Takeaways
- Avoid heavy plugins by using PHP's native GD library for image conversion.
- Convert at upload time so every image is already optimized before it's ever served.
- Correctly preserve alpha channels when converting PNG files to avoid solid black backgrounds.
- Implement strict memory management practices (
imagedestroy()) to prevent server crashes during bulk operations.
Why GD is enough
GD comes bundled with almost every PHP install, so there's usually nothing to set up. It can create, resize, and re-encode images on the server, and since PHP 7.1 it reads and writes WebP directly through imagewebp(). If you want to confirm it's available on your host, gd_info() will list WebP support.
Doing the conversion here, in your own upload code, means you're not depending on a browser extension, a build step, or a paid CDN transform to get optimized images out the door.
Basic Implementation: JPEG to WebP
Converting standard product photography or hero banners is straightforward. Here is a clean, vanilla PHP implementation that takes an uploaded JPEG file, reads its pixel data into server memory, and writes it back to your storage disk as an optimized WebP.
<?php
/**
* Converts a standard JPEG image to WebP format.
*/
function convertJpegToWebp($sourcePath, $destinationPath, $quality = 80) {
// 1. Create a new image resource from the source file
$image = @imagecreatefromjpeg($sourcePath);
if (!$image) {
return false; // Invalid image or path
}
// 2. Save the image as WebP
// The quality parameter ranges from 0 (worst/smallest) to 100 (best/largest)
$success = imagewebp($image, $destinationPath, $quality);
// 3. Free up server memory
imagedestroy($image);
return $success;
}
// Example Execution:
$source = "uploads/heavy-product-photo.jpg";
$destination = "uploads/optimized-product-photo.webp";
if (convertJpegToWebp($source, $destination, 82)) {
echo "Image successfully converted and optimized!";
}
?>
Handling Transparency: PNG to WebP
Handling PNG files requires a slightly different approach. Because WebP supports an alpha channel, you must explicitly instruct the GD library to preserve the transparency of the source image. If you skip this critical step, any transparent background in your PNG will render as a solid black box in the resulting WebP file.
<?php
/**
* Converts a PNG image to WebP while preserving the alpha channel.
*/
function convertPngToWebp($sourcePath, $destinationPath, $quality = 80) {
$image = @imagecreatefrompng($sourcePath);
if (!$image) {
return false;
}
// Explicitly preserve transparency
imagepalettetotruecolor($image);
imagealphablending($image, true);
imagesavealpha($image, true);
// Generate the WebP
$success = imagewebp($image, $destinationPath, $quality);
// Cleanup
imagedestroy($image);
return $success;
}
?>
Memory Management Warning
Image processing is highly intensive on server RAM. Always ensure you call imagedestroy() immediately after writing your WebP file to disk. If you are running bulk conversion scripts across a large database, failing to destroy the image instances will rapidly exhaust your memory_limit and crash your server.
Conclusion
Wire these functions into your upload handler and the optimization stops being a chore you remember to do — every image is already WebP by the time it's stored. You keep a dependency out of your stack, and your pages get lighter without anyone on the team having to think about it again. Just don't forget the imagedestroy() calls if you batch-convert an existing library.
Need to optimize without writing code?
If you don't have access to your server's backend, you can achieve the exact same WebP compression locally using our free browser tool.
Optimize Images NowAbout WebPMagic
WebPMagic is an independent project focused on image optimization and web performance. These guides are researched and edited to give developers clear, practical, and accurate information for building faster websites, with tips drawn from hands-on use of our own WebP conversion tool. Found an error or have a suggestion? Let us know via our contact page.