PHP GD 擴展提供豐富的圖像顏色操作函數,適用於動態圖表、驗證碼、水印生成等場景。本文整理核心顏色相關函數,附帶語法說明與應用場景,方便快速查閱。
顏色分配與透明度
| 函數 | 語法 | 說明 | 應用場景 |
imagecolorallocate |
int imagecolorallocate(resource $image, int $red, int $green, int $blue) |
為指定圖像分配一個 RGB 顏色,返回顏色標識符。同一圖像中所有使用的顏色必須先分配,不同圖像間顏色標識不通用。 |
建立畫布後第一步,定義繪圖、填充、文字顏色。 |
imagecolortransparent |
int imagecolortransparent(resource $image [, int $color]) |
將指定顏色設為透明色。若省略 $color 則返回當前透明色標識。 |
製作透明背景 PNG/GIF,如 Logo、圖標。 |
像素顏色讀取與匹配
| 函數 | 語法 | 說明 |
imagecolorat |
int imagecolorat(resource $image, int $x, int $y) |
取得指定座標像素的顏色標識(整數),可搭配 imagecolorsforindex() 解析 RGB。 |
imagecolorclosest |
int imagecolorclosest(resource $image, int $red, int $green, int $blue) |
在圖像調色盤中尋找與指定 RGB 最接近的顏色索引。適用於調色盤模式圖像(GIF、8-bit PNG)。 |
imagecolorstotal |
int imagecolorstotal(resource $image) |
返回圖像調色盤中顏色總數(僅調色盤模式)。真彩色圖像返回 0。 |
調色盤操作(僅限調色盤模式圖像)
| 函數 | 語法 | 說明 |
imagecolorset |
bool imagecolorset(resource $image, int $index, int $red, int $green, int $blue) |
修改調色盤中指定索引的顏色值。所有使用該索引的像素顏色將同步改變。 |
imagecolorsforindex |
array imagecolorsforindex(resource $image, int $index) |
返回指定索引的 RGB 陣列:['red'=>r, 'green'=>g, 'blue'=>b, 'alpha'=>a]。 |
實用範例:建立真彩色圖像並繪製漸層文字
<?php
// 建立 400x200 真彩色畫布
$im = imagecreatetruecolor(400, 200);
// 分配顏色
$white = imagecolorallocate($im, 255, 255, 255);
$blue = imagecolorallocate($im, 0, 0, 255);
$red = imagecolorallocate($im, 255, 0, 0);
// 填充白色背景
imagefill($im, 0, 0, $white);
// 繪製漸層效果:從左到右藍變紅
for ($x = 0; $x < 400; $x++) {
$r = (int)($x / 400 * 255);
$b = 255 - $r;
$color = imagecolorallocate($im, $r, 0, $b);
imageline($im, $x, 50, $x, 150, $color);
}
// 輸出文字
imagestring($im, 5, 50, 10, 'GD Color Demo', $red);
// 輸出 PNG
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
?>
關鍵提醒
- 真彩色 vs 調色盤:
imagecreatetruecolor() 建立 24-bit 真彩色圖像,顏色數無上限,不使用調色盤;imagecreate() 建立 8-bit 調色盤圖像,最多 256 色,上述調色盤函數僅適用後者。
- 顏色標識符 為整數,真彩色模式下直接編碼 RGB 值(0xRRGGBB),調色盤模式下為索引值。
- Alpha 通道:真彩色模式支援透明度(0-127),可用
imagecolorallocatealpha() 分配。
- 完成繪圖後務必呼叫
imagedestroy() 釋放記憶體。
現代替代方案
對於複雜圖形處理,建議考慮 ImageMagick (imagick 擴展) 或 Intervention Image 套件,提供更豐富的 API 與更好的效能。