resize_image()最簡單的邏輯:取長邊為基準縮放,短邊等比縮小,直接回傳 GD 圖片資源。
<?php
/**
* 等比縮放並回傳圖片資源
*
* @param string $filename 原圖路徑
* @param string $tmpname 暫存路徑(實際同 $filename)
* @param int $xmax 最大寬度
* @param int $ymax 最大高度
* @return resource|false GD 圖片資源
*/
function resize_image(string $filename, string $tmpname, int $xmax, int $ymax) {
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$im = match ($ext) {
'jpg', 'jpeg' => imagecreatefromjpeg($tmpname),
'png' => imagecreatefrompng($tmpname),
'gif' => imagecreatefromgif($tmpname),
default => false,
};
if (!$im) return false;
$x = imagesx($im);
$y = imagesy($im);
// 原圖已小於限制,直接回傳
if ($x <= $xmax && $y <= $ymax) return $im;
// 計算新尺寸
if ($x >= $y) {
$newX = $xmax;
$newY = $newX * $y / $x;
} else {
$newY = $ymax;
$newX = $x / $y * $newY;
}
$im2 = imagecreatetruecolor($newX, $newY);
imagecopyresized($im2, $im, 0, 0, 0, 0, $newX, $newY, $x, $y);
return $im2;
}
?>
creat_thumbnail()支援 GIF/JPG/PNG 自動偵測、等比縮放、指定輸出路徑與品質。
<?php
/**
* 產生縮圖並存檔
*
* @param string $img 來源圖片路徑
* @param int $w 目標最大寬度
* @param int $h 目標最大高度
* @param string $path 輸出資料夾路徑
* @return string|false 縮圖完整路徑
*/
function creat_thumbnail(string $img, int $w, int $h, string $path) {
$info = getimagesize($img);
if (!$info) return false;
$origX = $info[0];
$origY = $info[1];
$origType = $info[2]; // 1=GIF, 2=JPG, 3=PNG
// 對應建立/輸出函式
$funcs = [
1 => ['create' => 'imagecreatefromgif', 'output' => 'imagegif', 'ext' => '.gif'],
2 => ['create' => 'imagecreatefromjpeg', 'output' => 'imagejpeg', 'ext' => '.jpg'],
3 => ['create' => 'imagecreatefrompng', 'output' => 'imagepng', 'ext' => '.png'],
];
if (!isset($funcs[$origType])) return false;
$create = $funcs[$origType]['create'];
$output = $funcs[$origType]['output'];
$ext = $funcs[$origType]['ext'];
$origImage = $create($img);
if (!$origImage) return false;
// 等比計算(以 4:3 為基準判斷橫/直)
if (($origX / $origY) >= (4/3)) {
$y = round($origY / ($origX / $w));
$x = $w;
} else {
$x = round($origX / ($origY / $h));
$y = $h;
}
$thumb = imagecreatetruecolor($x, $y);
imagecopyresampled($thumb, $origImage, 0, 0, 0, 0, $x, $y, $origX, $origY);
$fileName = $path . '/s_' . date('YmdHis') . $ext;
$result = $output($thumb, $fileName, 80); // 品質 80
imagedestroy($thumb);
imagedestroy($origImage);
return $result ? $fileName : false;
}
?>
imagepng($im, $file, 6) 設定壓縮等級。memory_limit,處理完立即 imagedestroy()。intervention/image,一行程式碼搞定縮圖、水印、濾鏡,且支援 Laravel 整合。