Convert Uploaded Images to WebP
Author: Kev Quirk |
Hook:
on_image_uploaded
Automatically converts uploaded images to WebP format and resizes them to a maximum of 1200px wide on upload. Requires the PHP gd extension.
Supports JPEG, PNG, WebP, and GIF source images. The original file is replaced by the converted WebP.
function on_image_uploaded(string $path): void
{
if (!extension_loaded('gd')) {
return;
}
$mime = mime_content_type($path) ?: '';
$image = match ($mime) {
'image/jpeg' => imagecreatefromjpeg($path),
'image/png' => imagecreatefrompng($path),
'image/webp' => imagecreatefromwebp($path),
'image/gif' => imagecreatefromgif($path),
default => false,
};
if ($image === false) {
return;
}
$origW = imagesx($image);
$origH = imagesy($image);
if ($origW > 1200) {
$newH = (int) round($origH * 1200 / $origW);
$resized = imagescale($image, 1200, $newH);
imagedestroy($image);
if ($resized === false) {
return;
}
$image = $resized;
}
$webpPath = preg_replace('/\.[^.]+$/', '.webp', $path) ?? $path;
imagewebp($image, $webpPath, 82);
imagedestroy($image);
if ($webpPath !== $path) {
unlink($path);
}
}