<?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.');
}
