PHP实现获取图片颜色值的方法
PHP获取图片颜色值检测图片主要颜色是通过imagecreatefromjpeg函数读取图片,再循环获得各个颜色值加以计算实现的。
/**
* 获取图片主要颜色
* @param $image
* @return array
*/
function dominant_color($image)
{
$rTotal = $gTotal = $bTotal = $total = 0;
$i = imagecreatefromjpeg($image);
for ($x = 0; $x < imagesx($i); $x++) {
for ($y = 0; $y < imagesy($i); $y++) {
$rgb = imagecolorat($i, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$rTotal += $r;
$gTotal += $g;
$bTotal += $b;
$total++;
}
}
$rAverage = round($rTotal / $total);
$gAverage = round($gTotal / $total);
$bAverage = round($bTotal / $total);
return array(
'r' => $rAverage,
'g' => $gAverage,
'b' => $bAverage,
);
}