PHP GD 擴展提供強大的影像處理能力,本文通過六個完整範例,由淺入深展示:環境檢測、基本繪圖流程、核心函數速查、藍底白線、陰陽圖、3D 扇形圖、簡易/進階驗證碼、圖片水印與縮圖生成。
if (!function_exists('imagecreate')) {
die('本伺服器不支援 GD 模組');
}
若不支援:下載 php_gd2.dll、修改 php.ini 啟用 extension=gd、重啟 Web 伺服器。
$img = imagecreatetruecolor($w, $h)(建議用 TrueColor)$color = imagecolorallocate($img, R, G, B)header('Content-Type: image/png'); imagepng($img) 或 imagepng($img, 'file.png')imagedestroy($img)| 函數 | 用途 | 關鍵參數 |
|---|---|---|
| imagecreatetruecolor | 建立真彩色畫布 | 寬、高 |
| imagecolorallocate | 分配顏色識別碼 | 畫布、R、G、B (0-255) |
| imagefill | 區域填充 | 畫布、起始座標、顏色 |
| imageline | 畫線段 | 畫布、兩端座標、顏色 |
| imagestring | 畫內建字體文字 | 畫布、字體號(1-5)、座標、字串、顏色 |
| imagettftext | 畫 TrueType 字體文字 | 畫布、大小、角度、座標、顏色、字體檔、字串 |
| imagefilledellipse | 畫實心橢圓 | 畫布、中心座標、寬高、顏色 |
| imagefilledarc | 畫實心弧形/扇形 | 畫布、中心、寬高、起止角度、顏色、模式 |
| imagesetthickness | 設定線條粗細 | 畫布、像素 |
| imagesetpixel | 畫單一像素 | 畫布、座標、顏色 |
| imagecopyresized | 複製並縮放 | 目標、來源、座標、寬高 |
$img = imagecreate(35, 35);
$white = imagecolorallocate($img, 255, 255, 255);
$blue = imagecolorallocate($img, 0, 0, 108);
imagefill($img, 0, 0, $blue);
imagesetthickness($img, 3);
imageline($img, 0, 0, 35, 35, $white);
imageline($img, 35, 0, 0, 35, $white);
header('Content-Type: image/png');
imagepng($img);
imagedestroy($img);
運用 imagefilledarc 繪製大圓與半圓,imagefilledellipse 繪製魚眼,展示圖層疊加技巧。
核心技巧:for ($i = $h/2+20; $i > $h/2; $i--) 向上疊加多層偏暗色扇形製造厚度感,最後在頂層繪製高亮色扇形。
| 特性 | 簡易版 (65×20) | 進階版 (600×100) |
|---|---|---|
| 字元來源 | 英數混合 62 字 | 同左 |
| 字體 | 內建 5 號字體 | TTF (Arial) + 隨機旋轉 ±120° |
| 顏色 | 隨機 RGB | 預設調色盤 + 隨機挑選 |
| 干擾 | 隨機像素點 | 密集像素點 (面積/100) |
| Session 儲存 | $_SESSION['cjjer'] | 同左 |
關鍵代碼片段 (進階版):
$fontSize = floor($height / 2);
for ($i = 0; $i < $strSize; $i++) {
$x = $fontSize + $i * $width / ($strSize + 1);
$y = $height / 2;
$angle = rand(-120, 120);
$color = imagecolorallocate($img, rand(0,255), rand(0,255), rand(0,255));
imagettftext($img, $fontSize, $angle, $x, $y, $color, $fontFile, $char);
}
$src = imagecreatefromjpeg('my.jpg');
$watermark = '我是帥哥,你是MM麼?';
$font = __DIR__ . '/simsun.ttc';
$text = iconv('GB2312', 'UTF-8', $watermark);
$red = imagecolorallocate($src, 111, 0, 0);
imagettftext($src, 30, 25, $w/5, $h/2, $red, $font, $text);
// 縮圖 50%
$dst = imagecreatetruecolor($w*0.5, $h*0.5);
imagecopyresized($dst, $src, 0,0,0,0, $w*0.5, $h*0.5, $w, $h);
imagejpeg($dst, 'my_zoom.jpg', 85);
imagedestroy($src); imagedestroy($dst);
格式選擇建議:相片類 → JPEG (品質 80-90);截圖/圖示 → PNG;動畫 → GIF。
iconv 轉 UTF-8 並載入中文字體 (如 simsun.ttc)memory_limit,及時 imagedestroyimagecreatetruecolor,支援 Alpha 透明與 1670 萬色header('Content-Type: image/png') 必須在任何輸出前GD 雖非 ImageMagick 那般強大,但零依賴、隨 PHP 內建、API 穩定,足以應對驗證碼、圖表、水印、縮圖等 90% 的 Web 圖形需求。掌握本文六大範例核心邏輯,即可靈活組合解決實際業務場景。