>我正在开发需要检测图像中混合颜色百分比的应用程序。如何在 PHP 中做到这一点?这是一个代码可以获取颜色的名称(RGB),但没有任何百分比的混合颜色。
<?php
function colorPalette($imageFile, $numColors, $granularity = 5)
{
$granularity = max(1, abs((int)$granularity));
$colors = array();
$size = @getimagesize($imageFile);
if($size === false)
{
user_error("Unable to get image size data");
return false;
}
$img = @imagecreatefromjpeg($imageFile);
if(!$img)
{
user_error("Unable to open image file");
return false;
}
for($x = 0; $x < $size[0]; $x += $granularity)
{
for($y = 0; $y < $size[1]; $y += $granularity)
{
$thisColor = imagecolorat($img, $x, $y);
$rgb = imagecolorsforindex($img, $thisColor);
$red = round(round(($rgb['red'] / 0x33)) * 0x33);
$green = round(round(($rgb['green'] / 0x33)) * 0x33);
$blue = round(round(($rgb['blue'] / 0x33)) * 0x33);
$thisRGB = sprintf('%02X%02X%02X', $red, $green, $blue);
if(array_key_exists($thisRGB, $colors))
{
$colors[$thisRGB]++;
}
else
{
$colors[$thisRGB] = 1;
}
}
}
arsort($colors);
return array_slice(array_keys($colors), 0, $numColors);
}
// sample usage:
$palette = colorPalette('te.jpg', 10, 4);
echo "<table>'n";
foreach($palette as $color)
{
echo "<tr><td style='background-color:#$color;width:2em;'> </td><td>#$color</td></tr>'n";
}
echo "</table>'n";
?>
红绿蓝的范围可以从0到0xFF(255)。已知:
$red = round(round(($rgb['red'] / 0x33)) * 0x33);
$green = round(round(($rgb['green'] / 0x33)) * 0x33);
$blue = round(round(($rgb['blue'] / 0x33)) * 0x33);
$percentRed = ($red / 0xFF) * 100;
$percentGreen = ($green / 0xFF) * 100;
$percentBlue = ($blue / 0xFF) * 100;
如果您想获得特定颜色在图片中出现次数的百分比,请使用类似以下内容:
$sum = array_sum($palette);
foreach($palette as $color => $count)
{
echo "<tr><td style='background-color:#$color;width:2em;'> </td><td>#$color (".(($count / $sum) * 100).")</td></tr>'n";
}
并替换
return array_slice(array_keys($colors), 0, $numColors);
由
return array_slice($colors, 0, $numColors, true);