<?php
function resizeImageMax(string $srcPath, string $dstPath, int $maxDim = 1024, int $quality = 85): void {
[$w, $h] = getimagesize($srcPath);
$scale = min(1.0, $maxDim / max($w, $h));
$newW = (int)round($w * $scale);
$newH = (int)round($h * $scale);
$src = match (mime_content_type($srcPath)) {
'image/jpeg' => imagecreatefromjpeg($srcPath),
'image/png' => imagecreatefrompng($srcPath),
'image/gif' => imagecreatefromgif($srcPath),
'image/webp' => imagecreatefromwebp($srcPath),
default => throw new RuntimeException('Unsupported image type'),
};
$dst = imagecreatetruecolor($newW, $newH);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newW, $newH, $w, $h);
imagejpeg($dst, $dstPath, $quality);
imagedestroy($src);
imagedestroy($dst);
}
resizeImageMax('/uploads/photo.png', '/uploads/photo-1024.jpg', 1024);
Create a free account and build your private vault. Share publicly whenever you want.