採用類別封裝 GD 圖片處理功能,支援 JPG/PNG/GIF 三種格式,提供浮水印(圖片/文字)與多種縮圖模式(固定寬/高、裁切、等比例)。
class Water {
// 浮水印設定
private $watermark_on = true;
public $water_img; // 浮水印圖片路徑
public $pos = 1; // 位置 1-9 (九宮格)
public $pct = 80; // 圖片浮水印透明度
public $quality = 80; // 輸出品質
public $text = 'Watermark';
public $size = 12; // 文字大小
public $color = '#000000';
public $font = 'font.ttf';
// 縮圖設定
private $thumb_on = true;
public $thumb_type = 1; // 1=寬固定, 2=高固定, 3=寬固定裁切高, 4=高固定裁切寬, 5=等比例
public $thumb_width;
public $thumb_height;
public $thumb_fix = '_thumb'; // 輸出檔名後綴
// 核心方法
public function thumb($img, $outfile='', $t_type='', $t_w='', $t_h='') { ... }
public function watermark($img, $pos='', $out_img='', $water_img='', $text='') { ... }
private function check($img) { ... } // 驗證檔案存在、格式支援
private function thumb_size($w, $h, $tw, $th, $type) { ... } // 計算目標尺寸
}
| 類型 | 行為 |
|---|---|
| 1 | 寬度固定,高度等比例縮放 |
| 2 | 高度固定,寬度等比例縮放 |
| 3 | 寬度固定,高度裁切(置中) |
| 4 | 高度固定,寬度裁切(置中) |
| 5 | 等比例縮放,長邊符合限制 |
1 2 3 4 5 6 ← 5 為置中 7 8 9
check() 確認副檔名、檔案存在、GD 載入imagecreatefromjpeg/png/gif()imagecopyresampled() 高品質重採樣imagecolortransparent()imagecopymerge(),文字用 imagettftext()imagejpeg/png/gif(),銷毀資源釋放記憶體$water = new Water();
$water->water_img = 'logo.png';
$water->pos = 5; // 置中
$water->pct = 50; // 50% 透明度
$water->text = 'MySite.com';
$water->size = 20;
$water->color = '#FFFFFF';
$water->font = '/path/to/font.ttf';
// 加浮水印
$water->watermark('photo.jpg', 5, 'photo_wm.jpg');
// 產生縮圖
$water->thumb_width = 300;
$water->thumb_height = 200;
$water->thumb_type = 1; // 寬度固定 300px
$water->thumb('photo.jpg', 'photo_thumb.jpg');
private function check_gifcartoon($file) {
$fp = fopen($file, 'rb');
$head = fread($fp, 1024);
fclose($fp);
// 偵測 NETSCAPE2.0 循環標識
return preg_match("/".chr(0x21).chr(0xFF).chr(0x0B).'NETSCAPE2.0'."/", $head) ? false : true;
}
動畫 GIF 僅處理第一幀,避免輸出損壞檔案。
將 GD 操作封裝為可配置類別,專案中即可輕鬆複用浮水印與縮圖功能,支援多種輸出模式滿足不同業務需求。