GD 擴展提供約 60 個函式,涵蓋建立畫布、繪製基本圖形、文字渲染、色彩管理、圖片輸入輸出、進階 TrueType 字體、圖片複製縮放等。本文將核心函式歸納為 8 大功能組,附上函式簽名與典型用途,方便開發時快速查找。
| 功能組 | 代表函式 | 核心用途 |
|---|---|---|
| 畫布建立/匯入 | imagecreate(w,h) |
建立調色盤模式畫布(舊式,不支援真彩色) |
imagecreatetruecolor(w,h) |
建立真彩色畫布(現代標準,支援 Alpha 通道) | |
imagecreatefromjpeg/png/gif/webp/bmp/string |
從檔案/字串建立圖片資源 | |
| 色彩分配/查詢 | imagecolorallocate(im, r,g,b) |
分配不透明色彩,回傳色彩索引 |
imagecolorallocatealpha(im, r,g,b, alpha) |
分配半透明色彩(0 不透明~127 完全透明) | |
imagecolorat/closest/exact/resolve |
取得/查找色彩索引 | |
| 基本繪圖 | imagesetpixel(im, x,y, color) |
畫單一像素 |
imageline/imagedashedline(im, x1,y1,x2,y2, color) |
實線/虛線 | |
imagerectangle/imagefilledrectangle(im, x1,y1,x2,y2, color) |
矩形框/填滿矩形 | |
imageellipse/imagefilledellipse(im, cx,cy, w,h, color) |
橢圓/填滿橢圓 | |
| 多邊形/弧形 | imagepolygon/imagefilledpolygon(im, points, num, color) |
多邊形(points 為 [x1,y1,x2,y2...]) |
imagearc(im, cx,cy, w,h, start,end, color) |
弧線(角度 0-360,3 點鐘方向為 0) | |
imagefilledarc(im, ..., style) |
填滿扇形(支援 IMG_ARC_PIE/CHORD/NOFILL/EDGED) | |
| 文字渲染 | imagestring/imagestringup(im, font, x,y, text, color) |
內建點陣字體(1-5),僅支援 ASCII |
imagechar/imagecharup(im, font, x,y, char, color) |
單字元繪製 | |
imagettftext(im, size, angle, x,y, color, fontfile, text) |
TrueType 字體(支援中文、Unicode、旋轉) | |
imagettfbbox(size, angle, fontfile, text) |
計算文字外接矩形(定位/換行必備) | |
| 圖片複製/縮放/合成 | imagecopy(dst, src, dx,dy, sx,sy, w,h) |
直複製(可做水印、切圖) |
imagecopyresampled(dst, src, dx,dy, sx,sy, dw,dh, sw,sh) |
高品質縮放(重採樣,抗鋸齒) | |
imagecopymerge(dst, src, ..., pct) |
帶透明度合成(pct 0-100) | |
| 輸出/銷毀 | imagejpeg/png/gif/webp/wbmp(im, filename?, quality) |
輸出檔案或直接輸出瀏覽器(配合 header) |
imagedestroy(im) |
釋放圖片資源記憶體(長腳本必做) | |
imagetypes() |
回傳當前 GD 支援的格式位元組合 | |
| 進階/特殊 | imagefilter(im, FILTER_*) |
濾鏡:灰階、銳化、高斯模糊、色階、反色等 |
imageaffine/imagerotate/imagetransform |
幾何變換(旋轉、仿射、翻轉) | |
imageinterlace(im, true) |
開啟漸進式 JPEG/隔行掃描 GIF/PNG |
<?php
// 1. 建立真彩畫布
$im = imagecreatetruecolor(120, 40);
// 2. 分配色彩
$bg = imagecolorallocate($im, 240, 240, 240);
$textColor = imagecolorallocate($im, 50, 50, 50);
$noiseColor = imagecolorallocatealpha($im, 100,100,100, 60);
// 3. 填背景
imagefill($im, 0, 0, $bg);
// 4. 干擾線/點
for ($i=0;$i<5;$i++) imageline($im, 0, mt_rand(0,40), 120, mt_rand(0,40), $noiseColor);
for ($i=0;$i<50;$i++) imagesetpixel($im, mt_rand(0,120), mt_rand(0,40), $noiseColor);
// 5. 繪製文字(需 TTF 字體檔)
$code = substr(str_shuffle('ABCDEFGHJKLMNPQRSTUVWXYZ23456789'), 0, 4);
$font = __DIR__.'/fonts/arial.ttf';
imagettftext($im, 20, mt_rand(-10,10), 15, 30, $textColor, $font, $code);
// 6. 輸出
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
// 7. 儲存驗證碼至 Session
$_SESSION['captcha'] = $code;
imagecreate* / imagecreatefrom* **必須** 配對 imagedestroy()。GdImage 物件,自動回收機制較佳,但顯式銷毀仍是好習慣。GD 函式雖多,但核心工作流固定為「建立畫布 → 分配色彩 → 繪圖/文字 → 複製合成 → 輸出 → 銷毀」。熟悉上表 8 大功能組與對應代表函式,即能應對驗證碼、圖表、水印、縮圖、海報合成等 95% 圖形處理需求。