萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 取得圖片平均顏色值:掃描像素累加 RGB 通道

遍歷圖片所有像素,累加 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);
?>

效能優化建議

  • 大圖先縮小再掃描(如縮至 100x100),大幅減少像素數。
  • 使用 imagecopyresampled 縮放至小尺寸後再 imagecolorat 採樣。
  • 若需更精準的主色調,可採用 K-means 聚類或直方圖統計。

輸出範例

平均顏色:RGB(123, 98, 76)
copyright © 萬盛學電腦網 all rights reserved