萬盛學電腦網

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

PHP 計算圖片平均顏色值實現主色調提取

原理

遍歷圖片每個像素,累加 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 倍以上,誤差可忽略。
  • 跳過透明像素:PNG 圖片檢查 alpha 通道,全透明像素不參與平均。
  • K-means 聚類:提取前 N 個主色而非單一平均色,效果更符合視覺感知。

擴展:生成調色板


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;
}
copyright © 萬盛學電腦網 all rights reserved