若需分析圖片的整體色調,可透過計算所有像素的 RGB 平均值來取得主要顏色。本文示範使用 GD 函數庫逐像素讀取並累加色彩通道,最後計算平均值。
imagecreatefromjpeg() 載入 JPEG 圖片資源。imagecolorat() 取得各像素的 RGB 整數值。$i = imagecreatefromjpeg("image.jpg");
$rTotal = $gTotal = $bTotal = $total = 0;
for ($x = 0; $x < imagesx($i); $x++) {
for ($y = 0; $y < imagesy($i); $y++) {
$rgb = imagecolorat($i, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$rTotal += $r;
$gTotal += $g;
$bTotal += $b;
$total++;
}
}
$rAverage = round($rTotal / $total);
$gAverage = round($gTotal / $total);
$bAverage = round($bTotal / $total);
echo "主要顏色 RGB: ($rAverage, $gAverage, $bAverage)";
imagecreatefrompng()、imagecreatefromgif() 等函數處理不同圖片類型。此方法簡單直觀,適合快速原型開發;若需更精準的色彩分析(如主導色、調色盤提取),可考慮使用 K-means 分群演算法或 ImageMagick 的進階功能。