遍歷圖片每個像素,累加 RGB 三通道值,最後取平均,即為圖片整體色調傾向。適用於縮略圖、色系分類、智能配色背景。
<?php
function getAverageColor($imagePath) {
if (!file_exists($imagePath)) return null;
$img = @imagecreatefromjpeg($imagePath); // 僅支持 JPEG,PNG 用 imagecreatefrompng
if (!$img) return null;
$width = imagesx($img);
$height = imagesy($img);
$total = $width * $height;
$rTotal = $gTotal = $bTotal = 0;
for ($x = 0; $x < $width; $x++) {
for ($y = 0; $y < $height; $y++) {
$rgb = imagecolorat($img, $x, $y);
$rTotal += ($rgb >> 16) & 0xFF;
$gTotal += ($rgb >> 8) & 0xFF;
$bTotal += $rgb & 0xFF;
}
}
imagedestroy($img); // 釋放 GD 資源
return [
'r' => intval(round($rTotal / $total)),
'g' => intval(round($gTotal / $total)),
'b' => intval(round($bTotal / $total)),
'hex' => sprintf('#%02X%02X%02X',
intval(round($rTotal / $total)),
intval(round($gTotal / $total)),
intval(round($bTotal / $total))
),
];
}
// 使用
$color = getAverageColor('photo3.jpg');
if ($color) {
echo "平均顏色:RGB({$color['r']}, {$color['g']}, {$color['b']}) HEX: {$color['hex']}";
echo "<div style='width:100px;height:50px;background:{$color['hex']}'></div>";
} else {
echo "圖片讀取失敗";
}
imagescale($img, 50, 50) 縮小至 50x50 再遍歷,速度提升 100 倍以上,誤差可忽略。
function getPalette($imagePath, $colorCount = 5) {
$img = imagecreatefromjpeg($imagePath);
$img = imagescale($img, 100, 100); // 縮小加速
$pixels = [];
for ($x=0;$x>16 & 0xFF, $rgb>>8 & 0xFF, $rgb & 0xFF];
}
imagedestroy($img);
// 簡易 K-means(此處略),返回前 $colorCount 個聚類中心
return $palette;
}