類別功能
- 支援 GIF/JPG/PNG 來源
- 縮略圖:保持比例、GD2
imagecreatetruecolor + ImageCopyResampled 高品質縮放
- 浮水印:半透明底帶 + 文字(需 TTF 字體檔),可自訂最大寬高
- 輸出模式:直接輸出瀏覽器或儲存檔案
核心代碼結構
class GDImage {
var $sourcePath, $galleryPath, $toFile = false, $fontName;
var $maxWidth = 500, $maxHeight = 600;
function __construct($sourcePath, $galleryPath, $fontPath) {
$this->sourcePath = $sourcePath;
$this->galleryPath = $galleryPath;
$this->fontName = $fontPath . "04B_08__.TTF";
}
function makeThumb($srcFile, $width=128, $height=128) {
// 1. getimagesize 取得資訊
// 2. 依型別 imagecreatefromgif/jpeg/png
// 3. 計算目標尺寸(保持比例)
// 4. GD2: imagecreatetruecolor + ImageCopyResampled
// 5. 輸出或儲存 JPEG
}
function waterMark($srcFile, $textArray) {
// 同樣建立真彩畫布縮放
// 繪製半透明矩形帶:imageColorAllocateAlpha + ImageFilledRectangle
// 寫入兩行文字:ImageTTFText
// 輸出或儲存
}
function getInfo($file) { return getimagesize($this->sourcePath . $file); }
}
使用範例
require_once("GDImage.inc.php");
header("Content-type: image/jpeg"); // 直接輸出模式
$img = new GDImage("/data/uploads/", "/data/thumbs/", "/fonts/");
$img->makeThumb("photo.jpg", 200, 150); // 產生縮略圖輸出
// 或
$img->toFile = true;
$path = $img->waterMark("photo.jpg", array("Copyright 2024", "MySite.com")); // 儲存浮水印版
關鍵技術點
ImageCopyResampled 重採樣品質遠優於 ImageCopyResized
- TTF 字體需預先備妥(範例用 04B_08__.TTF)
- 中文支援需額外處理(GB2312→Unicode),建議改用 FreeType + 字體子集化