首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 計算圖片主色調:基於 GD 庫像素採樣的平均 RGB 算法實作

     編輯:PHP 相關知識

透過 GD 库遍歷圖片像素計算平均 RGB 值,可快速取得圖片主色調,應用於縮圖背景填充、色系分類、動態 UI 主題生成等場景。本文提供完整實作與效能優化建議。

核心演算法:全像素平均法

<?php
function getDominantColor(string $imagePath, int $sampleStep = 1): array {
    // 1. 載入圖片資源
    $img = @imagecreatefromjpeg($imagePath);
    if (!$img) {
        throw new Exception("無法載入 JPEG 圖片:$imagePath");
    }

    $width = imagesx($img);
    $height = imagesy($img);

    // 2. 採樣累加(步長可調以平衡速度/精度)
    $rTotal = $gTotal = $bTotal = 0;
    $count = 0;

    for ($x = 0; $x < $width; $x += $sampleStep) {
        for ($y = 0; $y < $height; $y += $sampleStep) {
            $rgb = imagecolorat($img, $x, $y);
            $rTotal += ($rgb >> 16) & 0xFF;
            $gTotal += ($rgb >> 8) & 0xFF;
            $bTotal += $rgb & 0xFF;
            $count++;
        }
    }

    imagedestroy($img); // 釋放記憶體

    if ($count === 0) return [0, 0, 0];

    // 3. 計算平均值並四捨五入
    return [
        'r' => round($rTotal / $count),
        'g' => round($gTotal / $count),
        'b' => round($bTotal / $count),
        'hex' => sprintf('#%02x%02x%02x', 
            round($rTotal / $count), 
            round($gTotal / $count), 
            round($bTotal / $count)
        ),
        'sampled_pixels' => $count
    ];
}

// 使用範例
try {
    $color = getDominantColor('photo3.jpg', 5); // 每 5 像素採樣一次
    echo "主色調 RGB: {$color['r']}, {$color['g']}, {$color['b']}\n";
    echo "HEX: {$color['hex']}\n";
    echo "採樣像素數: {$color['sampled_pixels']}\n";
} catch (Exception $e) {
    echo '錯誤:' . $e->getMessage();
}
?>

效能優化關鍵參數

⚠️ 步長過大可能忽略細節色塊;建議上線前用實際圖片壓測調整。

進階改良方向

  1. K-means 聚類:將像素歸類為 3-5 群,取最大群質心,比平均法更能代表視覺主色。
  2. 排除背景色:先偵測四角像素判斷背景色,計算時排除相近顏色。
  3. 使用 ImageMagick:exec('convert image.jpg -scale 50x50! -depth 8 txt:-') 解析直方圖,速度更快且支援更多格式。
  4. 快取機制:以檔案 hash (md5_file) 為 key 存入 Redis/Memcached,避免重複計算。

多格式支援擴充

<?php
function createImageResource(string $path): ?\GdImage {
    $info = getimagesize($path);
    return match ($info[2] ?? 0) {
        IMAGETYPE_JPEG => imagecreatefromjpeg($path),
        IMAGETYPE_PNG  => imagecreatefrompng($path),
        IMAGETYPE_GIF  => imagecreatefromgif($path),
        IMAGETYPE_WEBP => imagecreatefromwebp($path),
        default => null
    };
}
?>

平均 RGB 法實作簡單、無外部依賴,適合中小型專案快速整合;追求精準視覺主色建議引入 K-means 或 ImageMagick 方案。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
圖片尺寸建議採樣步長預估採樣點數耗時參考
800×6005~19,200< 50ms
1920×108010~20,700< 80ms
4000×300020~30,000< 150ms