透過 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();
}
?>
| 圖片尺寸 | 建議採樣步長 | 預估採樣點數 | 耗時參考 |
|---|---|---|---|
| 800×600 | 5 | ~19,200 | < 50ms |
| 1920×1080 | 10 | ~20,700 | < 80ms |
| 4000×3000 | 20 | ~30,000 | < 150ms |