本文提供一個完整的 PHP 縮略圖生成範例,涵蓋檔案上傳驗證、圖片類型檢查、等比例縮放儲存全流程,適合快速整合至專案中。
<form method="post" action="suo_do.php" enctype="multipart/form-data">
<input type="file" name="pic" />
<input type="submit" value="上傳" />
</form>
<?php
header("Content-Type: text/html; charset=utf-8");
date_default_timezone_set("Asia/Chongqing");
// 1. 基礎驗證
if (empty($_FILES)) {
exit("上傳檔案過大或為空");
}
if ($_FILES['pic']['error'] !== UPLOAD_ERR_OK) {
exit("上傳失敗,錯誤代碼:" . $_FILES['pic']['error']);
}
// 2. 檔案類型白名單
$allowExt = ['jpg', 'png', 'jpeg', 'gif'];
$ext = strtolower(pathinfo($_FILES['pic']['name'], PATHINFO_EXTENSION));
if (!in_array($ext, $allowExt)) {
exit("不支援的檔案格式");
}
// 3. 生成唯一檔名並移動
$filename = date('YmdHis') . mt_rand(1000, 9999) . '.' . $ext;
$src = $_FILES['pic']['tmp_name'];
$destDir = __DIR__ . '/upload/';
if (!is_dir($destDir)) mkdir($destDir, 0755, true);
$dest = $destDir . $filename;
if (!move_uploaded_file($src, $dest)) {
exit("檔案儲存失敗");
}
// 4. 等比例生成縮略圖 (長邊 300px)
list($w, $h) = getimagesize($dest);
$maxSide = 300;
if ($w > $h) {
$newW = $maxSide;
$newH = round($maxSide * $h / $w);
} elseif ($w < $h) {
$newH = $maxSide;
$newW = round($maxSide * $w / $h);
} else {
$newW = $newH = $maxSide;
}
// 根據副檔名選擇正確的建立函式
switch ($ext) {
case 'jpg':
case 'jpeg':
$srcImg = imagecreatefromjpeg($dest);
break;
case 'png':
$srcImg = imagecreatefrompng($dest);
break;
case 'gif':
$srcImg = imagecreatefromgif($dest);
break;
default:
exit("未知圖片格式");
}
$thumbImg = imagecreatetruecolor($newW, $newH);
// PNG/GIF 保持透明度
if ($ext === 'png' || $ext === 'gif') {
imagealphablending($thumbImg, false);
imagesavealpha($thumbImg, true);
$transparent = imagecolorallocatealpha($thumbImg, 255, 255, 255, 127);
imagefilledrectangle($thumbImg, 0, 0, $newW, $newH, $transparent);
}
imagecopyresampled($thumbImg, $srcImg, 0, 0, 0, 0, $newW, $newH, $w, $h);
$thumbPath = $destDir . 's_' . $filename;
imagejpeg($thumbImg, $thumbPath, 85); // 統一輸出 JPEG,可依需求調整
imagedestroy($srcImg);
imagedestroy($thumbImg);
echo "縮略圖已生成:查看";
?>
imagecopyresampled 而非 imagecopyresized,品質更佳。$ext 分別呼叫 imagepng/imagegif。finfo_file)與檔案大小限制。