完整流程:表單上傳 → 類型/大小驗證 → 移動檔案 → 等比縮放 → 輸出縮略圖。
<form method="post" action="thumb.php" enctype="multipart/form-data">
<input type="file" name="pic" accept="image/*" />
<input type="submit" value="上傳並生成縮略圖" />
</form>
thumb.php<?php
header('Content-Type: text/html; charset=utf-8');
date_default_timezone_set('Asia/Shanghai');
$allowExt = ['jpg', 'jpeg', 'png', 'gif'];
$maxSize = 5 * 1024 * 1024; // 5MB
$thumbDir = __DIR__ . '/upload/';
$thumbMax = 300; // 縮略圖最長邊 300px
if (!isset($_FILES['pic']) || $_FILES['pic']['error'] !== UPLOAD_ERR_OK) {
exit('上傳失敗或檔案過大');
}
$ext = strtolower(pathinfo($_FILES['pic']['name'], PATHINFO_EXTENSION));
if (!in_array($ext, $allowExt)) {
exit('不允許的檔案類型');
}
if ($_FILES['pic']['size'] > $maxSize) {
exit('檔案超過 5MB 限制');
}
// 產生唯一檔名
$filename = date('YmdHis') . '_' . mt_rand(1000, 9999) . '.' . $ext;
$srcPath = $_FILES['pic']['tmp_name'];
$destPath = $thumbDir . $filename;
if (!move_uploaded_file($srcPath, $destPath)) {
exit('檔案移動失敗');
}
// === 縮略圖生成 ===
list($w, $h, $type) = getimagesize($destPath);
// 根據型別建立圖像資源
switch ($type) {
case IMAGETYPE_JPEG: $srcImg = imagecreatefromjpeg($destPath); break;
case IMAGETYPE_PNG: $srcImg = imagecreatefrompng($destPath); break;
case IMAGETYPE_GIF: $srcImg = imagecreatefromgif($destPath); break;
default: exit('不支援的圖片格式');
}
// 計算等比縮放尺寸
if ($w > $h) {
$newW = $thumbMax;
$newH = round($thumbMax * $h / $w);
} elseif ($w < $h) {
$newH = $thumbMax;
$newW = round($thumbMax * $w / $h);
} else {
$newW = $newH = $thumbMax;
}
// 建立真彩色畫布
$thumbImg = imagecreatetruecolor($newW, $newH);
// PNG/GIF 保留透明度
if ($type === IMAGETYPE_PNG || $type === IMAGETYPE_GIF) {
imagealphablending($thumbImg, false);
imagesavealpha($thumbImg, true);
$transparent = imagecolorallocatealpha($thumbImg, 0, 0, 0, 127);
imagefilledrectangle($thumbImg, 0, 0, $newW, $newH, $transparent);
}
// 複製並重採樣(品質優於 imagecopyresized)
imagecopyresampled($thumbImg, $srcImg, 0, 0, 0, 0, $newW, $newH, $w, $h);
// 輸出縮略圖
$thumbName = 'thumb_' . $filename;
$thumbPath = $thumbDir . $thumbName;
switch ($type) {
case IMAGETYPE_JPEG: imagejpeg($thumbImg, $thumbPath, 85); break;
case IMAGETYPE_PNG: imagepng($thumbImg, $thumbPath, 8); break;
case IMAGETYPE_GIF: imagegif($thumbImg, $thumbPath); break;
}
// 釋放資源
imagedestroy($srcImg);
imagedestroy($thumbImg);
echo "原圖:$destPath
縮略圖:$thumbPath";
imagecopyresampled 而非 imagecopyresized,品質更好。imagesavealpha 保留透明通道。chmod 755 且禁止腳本執行(Nginx/Apache 配置)。