遍歷圖片所有像素,累加 R/G/B 通道值並取平均,可獲得圖片整體主色調,適用於縮圖著色、主題色提取等場景。
<?php
$img = imagecreatefromjpeg('photo3.jpg'); // 需 GD 擴充
$w = imagesx($img);
$h = imagesy($img);
$rTotal = $gTotal = $bTotal = 0;
$total = 0;
for ($x = 0; $x < $w; $x++) {
for ($y = 0; $y < $h; $y++) {
$rgb = imagecolorat($img, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$rTotal += $r;
$gTotal += $g;
$bTotal += $b;
$total++;
}
}
$rAvg = round($rTotal / $total);
$gAvg = round($gTotal / $total);
$bAvg = round($bTotal / $total);
echo "平均顏色:RGB($rAvg, $gAvg, $bAvg)";
imagedestroy($img);
?>
imagecopyresampled 縮放至小尺寸後再 imagecolorat 採樣。平均顏色:RGB(123, 98, 76)