基本概念
- 圖片本質是二進位檔案,瀏覽器依
Content-Type 標頭決定如何渲染。
- PHP 輸出圖片時必須先送出
header('Content-Type: image/jpeg') 等標頭,且不可有任何額外輸出。
GD 函數分類速查
| 分類 | 代表函數 |
| 建立畫布 | imagecreate(), imagecreatetruecolor(), imagecreatefromjpeg/png/gif() |
| 顏色分配 | imagecolorallocate(), imagecolorallocatealpha() |
| 繪製文字 | imagestring(), imagettftext() (需 TTF 字體) |
| 繪製幾何 | imageline(), imagerectangle(), imageellipse(), imagefilledpolygon() |
| 圖片複製/縮放 | imagecopy(), imagecopyresampled(), imagecopymerge() |
| 輸出/儲存 | imagejpeg(), imagepng(), imagegif(), imagewbmp() |
實戰範例:縮略圖產生
<?php
function makeThumbnail($srcPath, $dstPath, $maxW, $maxQ, $quality=85)
{
list($ow, $oh) = getimagesize($srcPath);
$ratio = min($maxW/$ow, $maxQ/$oh);
$nw = (int)($ow * $ratio);
$nh = (int)($oh * $ratio);
$src = imagecreatefromjpeg($srcPath); // 依實際類型調整
$dst = imagecreatetruecolor($nw, $nh);
imagecopyresampled($dst, $src, 0,0, 0,0, $nw,$nh, $ow,$oh);
imagejpeg($dst, $dstPath, $quality);
imagedestroy($src);
imagedestroy($dst);
}
?>
關鍵技巧
- TrueColor 畫布:
imagecreatetruecolor() 支援 24-bit 色彩,縮圖品質遠優於 imagecreate()。
imagecopyresampled() 內建雙三次取樣,縮放品質優於 imagecopyresized()。
- 中文文字:必須使用
imagettftext() 載入 .ttf 字體,且字串為 UTF-8 編碼。
- 水印:載入水印圖 →
imagecopymerge() 疊加至主圖指定座標。
- 直接輸出:腳本只能輸出圖片二進位,不可混入 HTML,調用時用
<img src="thumb.php?id=123" />。
常見錯誤
- 忘記送出
header() 導致瀏覽器顯示亂碼。
- 輸出前有 BOM、空白行、錯誤訊息污染圖片資料流。
- 字體路徑錯誤導致
imagettftext() 失敗。