Last updated: August 28, 2026.
Generate thumbnails during upload or in a background job. Preserve the aspect ratio and resample the source instead of stretching it.
Resize and encode
<?php
$source = imagecreatefromjpeg(__DIR__ . '/photo.jpg');
if ($source === false) throw new RuntimeException('Invalid JPEG.');
$width = imagesx($source); $height = imagesy($source);
$newWidth = min(480, $width);
$newHeight = (int) round($height * $newWidth / $width);
$thumb = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
if (!imagewebp($thumb, __DIR__ . '/photo-thumb.webp', 82)) throw new RuntimeException('Write failed.');
imagedestroy($source); imagedestroy($thumb);Production checks
- Confirm that GD includes WebP support.
- Cap source dimensions to control memory use.
- Keep the original when later edits may need it.
- Test visual quality on photos and graphics.
Reference: PHP imagewebp reference.