分享一個完整的 PHP GD 庫生成縮略圖範例,涵蓋檔案上傳、類型驗證、隨機命名、等比縮放等實用功能,適合初學者參考學習。
<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("上傳檔案過大或為空");
}
// 2. 檢查上傳錯誤代碼
if ($_FILES['pic']['error'] !== UPLOAD_ERR_OK) {
exit("上傳失敗,錯誤代碼: " . $_FILES['pic']['error']);
}
// 3. 驗證檔案類型(僅允許圖片)
$allowTypes = ['jpg', 'png', 'jpeg', 'gif'];
$ext = strtolower(pathinfo($_FILES['pic']['name'], PATHINFO_EXTENSION));
if (!in_array($ext, $allowTypes)) {
exit("不支援的檔案類型,僅允許: " . implode(', ', $allowTypes));
}
// 4. 生成唯一檔名並移動
$filename = date('YmdHis') . '_' . mt_rand(1000, 9999) . '.' . $ext;
$src = $_FILES['pic']['tmp_name'];
$dest = 'upload/' . $filename;
if (!move_uploaded_file($src, $dest)) {
exit("檔案移動失敗,請檢查 upload 目錄權限");
}
// 5. 讀取圖片資訊並計算縮略尺寸(長邊固定 300px,等比縮放)
$image = imagecreatefromjpeg($dest); // 注意:實際應根據類型選擇 createfromjpeg/png/gif
$size = getimagesize($dest);
$w = $size[0];
$h = $size[1];
if ($w > $h) {
$newW = 300;
$newH = round($newW / $w * $h);
} elseif ($w < $h) {
$newH = 300;
$newW = round($newH / $h * $w);
} else {
$newW = $newH = 300;
}
// 6. 建立真彩色畫布並重採樣(imagecopyresampled 品質優於 imagecopyresized)
$thumb = imagecreatetruecolor($newW, $newH);
imagecopyresampled($thumb, $image, 0, 0, 0, 0, $newW, $newH, $w, $h);
// 7. 輸出縮略圖
$thumbPath = 'upload/s_' . $filename;
imagejpeg($thumb, $thumbPath, 85); // 85% 品質
// 釋放資源
imagedestroy($image);
imagedestroy($thumb);
echo "縮略圖生成成功:$thumbPath";
?>
UPLOAD_ERR_OK 常數判斷上傳狀態pathinfo() 更可靠imagecopyresampled 替代 imagecopyresized,縮略圖更銳利注意:範例中僅示範 JPEG 處理,實際專案請根據 getimagesize() 回傳的 MIME 類型,動態選擇 imagecreatefromjpeg/png/gif/webp 及對應的輸出函數。