GD 庫是 PHP 內建的圖形處理擴展,可動態生成圖片。本文示範如何用 GD 繪製標準比例的五星紅旗,涵蓋畫布建立、顏色分配、多邊形繪製等核心技術。
<?php
header("Content-Type: image/jpeg");
// 1. 建立 700x410 真彩色畫布(背景預設黑色)
$img = imagecreatetruecolor(700, 410);
// 2. 分配顏色:紅色背景、黃色五星
$red = imagecolorallocate($img, 255, 0, 0);
$yellow = imagecolorallocate($img, 237, 231, 32);
// 3. 填充紅色背景
imagefill($img, 0, 0, $red);
// 4. 定義五顆星星的頂點座標(每顆星 10 個頂點)
// 大星星
$a = array(90, 30, 108, 73, 157, 73, 119, 102, 135, 152, 93, 123, 52, 152, 66, 102, 29, 74, 76, 73, 90, 30);
// 四顆小星星
$a1 = array(229, 25, 229, 43, 248, 48, 229, 55, 229, 74, 217, 60, 198, 66, 210, 50, 197, 34, 218, 39, 229, 25);
$a2 = array(227, 108, 227, 127, 245, 134, 228, 139, 227, 157, 215, 143, 196, 149, 208, 132, 196, 117, 215, 122, 227, 108);
$a3 = array(163, 184, 163, 204, 181, 211, 163, 216, 163, 234, 152, 220, 132, 225, 144, 209, 132, 193, 151, 199, 163, 184);
$a4 = array(65, 209, 65, 228, 84, 235, 65, 240, 65, 259, 54, 245, 33, 249, 46, 233, 34, 217, 53, 224, 68, 209);
// 5. 繪製填充多邊形
imagefilledpolygon($img, $a, 11, $yellow); // 11 = 頂點數 = 22/2
imagefilledpolygon($img, $a1, 11, $yellow);
imagefilledpolygon($img, $a2, 11, $yellow);
imagefilledpolygon($img, $a3, 11, $yellow);
imagefilledpolygon($img, $a4, 11, $yellow);
// 6. 輸出並釋放資源
ob_clean(); // 清除先前輸出緩衝(防止干擾圖片資料流)
imagejpeg($img); // 輸出 JPEG
imagedestroy($img); // 釋放記憶體
?>
GD 畫布原點 (0,0) 在左上角,X 向右,Y 向下。座標陣列格式為 [x1, y1, x2, y2, ...],頂點數 = 陣列長度 / 2。
五角星由 5 個外角頂點 + 5 個內角頂點組成,共 10 點。本範例座標為預計算的固定值,實際專案中建議封裝函數:
function generateStar($cx, $cy, $outerR, $innerR, $rotation = 0) {
$points = [];
for ($i = 0; $i < 10; $i++) {
$angle = $rotation + $i * M_PI / 5;
$r = ($i % 2 == 0) ? $outerR : $innerR;
$points[] = $cx + $r * cos($angle);
$points[] = $cy + $r * sin($angle);
}
return $points;
}
若腳本前有空白字元、BOM 標記或錯誤訊息輸出,會混入圖片二進位資料導致圖片損壞。ob_clean() 確保輸出純淨的 JPEG 資料流。
imagettftext())掌握 GD 基礎繪圖,為 PHP 圖形化應用奠定堅實基礎。