首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫

PHP 利用 GD 庫生成縮略圖完整範例(含上傳驗證)

     編輯:MySQL 資料庫相關知識

完整流程:表單上傳 → 類型/大小驗證 → 移動檔案 → 等比縮放 → 輸出縮略圖。

1. HTML 表單

<form method="post" action="thumb.php" enctype="multipart/form-data">
  <input type="file" name="pic" accept="image/*" />
  <input type="submit" value="上傳並生成縮略圖" />
</form>

2. PHP 處理腳本 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,品質更好。
  • PNG/GIF 需手動開啟 imagesavealpha 保留透明通道。
  • JPEG 輸出品質 85 平衡體積與清晰度。
  • 上傳目錄需設定 chmod 755 且禁止腳本執行(Nginx/Apache 配置)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved