<?php
$file = 'photo.jpg';
$scale = 0.5; // 縮小 50%
header('Content-Type: image/jpeg');
list($w, $h) = getimagesize($file);
$nw = (int)($w * $scale);
$nh = (int)($h * $scale);
$dst = imagecreatetruecolor($nw, $nh);
$src = imagecreatefromjpeg($file);
imagecopyresampled($dst, $src, 0,0,0,0, $nw,$nh, $w,$h);
imagejpeg($dst, null, 100); // 直接輸出,品質 100
imagedestroy($dst); imagedestroy($src);
?>
<?php
function resizeFit($srcFile, $maxW, $maxH, $outFile = null, $quality = 90) {
$info = getimagesize($srcFile);
$ratio = min($maxW/$info[0], $maxH/$info[1], 1); // 不放大
$nw = (int)($info[0] * $ratio);
$nh = (int)($info[1] * $ratio);
$src = loadAny($srcFile); // 依類型載入
$dst = imagecreatetruecolor($nw, $nh);
// 透明支援
if (in_array($info[2], [IMAGETYPE_PNG, IMAGETYPE_GIF])) {
imagealphablending($dst, false);
imagesavealpha($dst, true);
$tr = imagecolorallocatealpha($dst, 0,0,0, 127);
imagefill($dst, 0,0, $tr);
}
imagecopyresampled($dst, $src, 0,0,0,0, $nw,$nh, $info[0],$info[1]);
if ($outFile) saveAny($dst, $outFile, $info[2], $quality);
else { header('Content-Type: '.$info['mime']); outputAny($dst, $info[2], $quality); }
imagedestroy($src); imagedestroy($dst);
}
function loadAny($f) {
$t = (getimagesize($f))[2];
return match($t) {
IMAGETYPE_JPEG => imagecreatefromjpeg($f),
IMAGETYPE_PNG => imagecreatefrompng($f),
IMAGETYPE_GIF => imagecreatefromgif($f),
default => null
};
}
function saveAny($im, $f, $type, $q) {
match($type) {
IMAGETYPE_JPEG => imagejpeg($im, $f, $q),
IMAGETYPE_PNG => imagepng($im, $f),
IMAGETYPE_GIF => imagegif($im, $f),
};
}
function outputAny($im, $type, $q) {
match($type) {
IMAGETYPE_JPEG => imagejpeg($im, null, $q),
IMAGETYPE_PNG => imagepng($im),
IMAGETYPE_GIF => imagegif($im),
};
}
// 用法
resizeFit('upload.jpg', 800, 600, 'thumb_800x600.jpg');
?>