GD 擴充套件是 PHP 內建的圖形處理引擎,掌握其核心 API 能快速實作驗證碼、圖表、浮水印、縮圖等功能。本文整理 12 個遞進式範例,從建立畫布到完整驗證碼程式,適合初學者循序漸進掌握 GD 核心概念。
$width = 200; $height = 200;
$img = imagecreatetruecolor($width, $height) or die("不支援 GD");
imagepng($img);
imagedestroy($img);
重點:imagecreatetruecolor 建立真彩畫布 (24-bit);imagepng 輸出二進位;imagedestroy 釋放記憶體。
$img = imagecreatetruecolor(200, 200);
$bg = imagecolorallocate($img, 255, 0, 0); // RGB 紅
imagefill($img, 0, 0, $bg);
imagepng($img); imagedestroy($img);
重點:imagecolorallocate 分配調色盤索引;imagefill 從 (0,0) 填滿。
$img = imagecreatetruecolor(200, 300);
$white = imagecolorallocate($img, 255,255,255);
imageline($img, 0, 40, 200, 40, $white); // 上橫線
imageline($img, 0, 260, 200, 260, $white); // 下橫線
imagepng($img); imagedestroy($img);
重點:imageline($im, x1, y1, x2, y2, $color) 座標原點在左上角。
$img = imagecreatetruecolor(200, 300);
$white = imagecolorallocate($img, 255,255,255);
imageline($img, 0, 40, 200, 40, $white);
imageline($img, 0, 260, 200, 260, $white);
imagestring($img, 5, 0, 60, "it's time to learn php!", $white); // 字型 1-5
imagepng($img); imagedestroy($img);
重點:imagestring 僅支援 Latin-1,字型 1-5 為內建點陣字體。
$img = imagecreatetruecolor(200, 300);
$white = imagecolorallocate($img, 255,255,255);
$font = "c:/windows/fonts/simli.ttf"; // 隸書
// 十六進位 UTF-8 組字 (舊式寫法)
$c1 = chr(0xe8).chr(0xa5).chr(0xbf); // 西
$c2 = chr(0xe6).chr(0xb8).chr(0xb8); // 遊
$c3 = chr(0xe8).chr(0xae).chr(0xb0); // 記
imagettftext($img, 30, 0, 10, 80, $white, $font, $c1);
imagettftext($img, 30, 0, 10, 120, $white, $font, $c2);
imagettftext($img, 30, 0, 10, 160, $white, $font, $c3);
// 現代寫法:直接用 UTF-8 字串 (PHP 檔案需儲存為 UTF-8)
imagettftext($img, 15, 0, 90, 254, $white, $font, "吳承恩著");
重點:imagettftext 需 FreeType 支援;座標 x,y 為基線左下角;角度逆時針度數。
$img = imagecreatefromjpeg("tower.jpg");
imagejpeg($img);
imagedestroy($img);
同類函式:imagecreatefromgif/png/webp/bmp。
$img = imagecreatefromjpeg("tower.jpg");
$x = imagesx($img); $y = imagesy($img);
echo "寬:$x px, 高:$y px";
imagedestroy($img);
getimagesize() 完整資訊$info = getimagesize("tower.jpg");
// $info[0]=寬, [1]=高, [2]=類型常數(1=GIF,2=JPEG,3=PNG...), [3]=HTML屬性字串
// $info['bits'], ['channels'], ['mime']
for ($i=0; $i<4; $i++) echo $info[$i]."<br/>";
$dst = imagecreatefromjpeg("photo.jpg");
$watermark = imagecreatefrompng("logo.png"); // 含透明通道
$dstW = imagesx($dst); $dstH = imagesy($dst);
$wmW = imagesx($watermark); $wmH = imagesy($watermark);
// 右下角留 10px 邊距
imagecopy($dst, $watermark, $dstW-$wmW-10, $dstH-$wmH-10, 0,0, $wmW,$wmH);
imagejpeg($dst, "photo_wm.jpg");
imagedestroy($dst); imagedestroy($watermark);
$src = imagecreatefromjpeg("photo.jpg");
$srcW = imagesx($src); $srcH = imagesy($src);
$maxW = 200; $maxH = 200;
$ratio = min($maxW/$srcW, $maxH/$srcH);
$newW = (int)($srcW*$ratio); $newH = (int)($srcH*$ratio);
$thumb = imagecreatetruecolor($newW, $newH);
imagecopyresampled($thumb, $src, 0,0,0,0, $newW,$newH, $srcW,$srcH);
imagejpeg($thumb, "thumb.jpg", 90);
imagedestroy($src); imagedestroy($thumb);
imagecopyresampled() 高畫質縮放已在範例 10 示範。關鍵差異:
imagecopyresized:最近鄰插值,鋸齒明顯、速度快。imagecopyresampled:雙三次插值,平滑銳利、速度稍慢,生產環境首選。<?php
session_start();
header("Content-Type: image/png");
$im = imagecreatetruecolor(100, 36);
$bg = imagecolorallocate($im, 240,240,240);
$textColor = imagecolorallocate($im, 0,0,0);
$noise = imagecolorallocate($im, 180,180,180);
imagefill($im, 0, 0, $bg);
// 干擾線
for($i=0;$i<6;$i++) imageline($im, rand(0,100), rand(0,36), rand(0,100), rand(0,36), $noise);
// 干擾點
for($i=0;$i<80;$i++) imagesetpixel($im, rand(0,100), rand(0,36), $noise);
// 4 碼驗證碼
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$code = '';
for($i=0;$i<4;$i++) $code .= $chars[rand(0, strlen($chars)-1)];
$_SESSION['captcha'] = strtoupper($code);
// 逐字繪製 (隨機旋轉/位移)
$x = 10;
for($i=0;$i<4;$i++) {
imagettftext($im, 20, rand(-10,10), $x, rand(24,30), $textColor,
__DIR__.'/fonts/DejaVuSans.ttf', $code[$i]);
$x += 20;
}
imagepng($im);
imagedestroy($im);
| 分類 | 函式 | 用途 |
|---|---|---|
| 建立畫布 | imagecreatetruecolor(w,h) | 真彩畫布 (建議) |
| imagecreate(w,h) | 調色盤畫布 (256 色,舊版相容) | |
| imagecreatefrom* (jpeg/png/gif/webp/bmp) | 從檔案/字串建立資源 | |
| 顏色 | imagecolorallocate(im, r,g,b) | 分配不透明色 |
| imagecolorallocatealpha(im, r,g,b, alpha) | 分配半透明色 (0=不透明, 127=全透明) | |
| imagecolortransparent(im, color) | 設定透明色索引 | |
| 繪圖 | imageline(im, x1,y1, x2,y2, c) | 直線 |
| imagerectangle/ellipse/arc | 矩形/橢圓/弧 | |
| imagefilled* | 填滿版本 | |
| imagettftext(im, size, angle, x, y, c, font, text) | TrueType 文字 | |
| 複製/縮放 | imagecopy(dst, src, dx,dy, sx,sy, sw,sh) | 像素級複製 |
| imagecopyresized(...) | 縮放複製 (低畫質) | |
| imagecopyresampled(...) | 縮放複製 (高畫質) | |
| 輸出 | imagejpeg/png/gif/webp(im, file?, quality?) | 輸出檔案/瀏覽器 |
| imagepng(im, file, compress_level 0-9) | PNG 壓縮等級 | |
| imagedestroy(im) | 釋放資源 |
__DIR__.'/fonts/xxx.ttf',確認 freetype 編譯支援。ini_set('memory_limit', '256M'),處理完立即 imagedestroy()。header() 前不能有任何輸出,檢查 ?> 後是否有換行。這 12 個範例涵蓋 GD 從建立、繪圖、文字、讀檔、屬性、浮水印、縮圖、驗證碼的完整入門路徑。建議實際動手執行每個範例,觀察輸出結果,再嘗試修改參數 (顏色、座標、字體、尺寸) 體會差異。掌握核心 API 後,即可著手開發圖表、報表、海報生成等實務功能。