Overview
Resize JPEG images proportionally with PHP GD after checking dimensions and pixel limits.
What this script does
This starter demonstrates proportional JPEG resizing with GD. It checks the decoded image dimensions and applies a pixel-count limit before processing.
Source code
<?php
declare(strict_types=1);
function resizeJpeg(string $source,string $destination,int $maxWidth=1600): void {
$info=getimagesize($source);
if (!$info || $info[2]!==IMAGETYPE_JPEG || $info[0]*$info[1]>24000000) throw new RuntimeException('Invalid image.');
$src=imagecreatefromjpeg($source);
if (!$src) throw new RuntimeException('Cannot decode image.');
$scale=min(1,$maxWidth/$info[0]); $w=max(1,(int)round($info[0]*$scale)); $h=max(1,(int)round($info[1]*$scale));
$dst=imagecreatetruecolor($w,$h);
imagecopyresampled($dst,$src,0,0,0,0,$w,$h,$info[0],$info[1]);
$ok=imagejpeg($dst,$destination,85); imagedestroy($src); imagedestroy($dst);
if (!$ok) throw new RuntimeException('Cannot save image.');
}
Download starter source: Download PHP JPEG Image Resizing with GD source
Installation and customization
- Enable the PHP GD extension.
- Review the source and configure a private destination directory.
- Add upload validation, authorization and rate limiting if accepting public uploads.
- Test large and malformed images before deployment.
> This is a learning starter, not a complete production upload application.