PHP颜色识别脚本返回错误的颜色

时间:2013-12-17 11:04:21

标签: php function colors

我遇到了这个我不理解的脚本的问题。

据我所知,一切都是正确的。该脚本确实有效,即使在循环中也能按预期返回颜色。

问题是输出的颜色不正确......

我删除了扫描图像并返回颜色数组的功能,并使用预设的绿色作为测试。该剧本认为它更接近红色,即使绿色值相同!

计算出该块的最小色差:

function getColor($rgb)
{

$colors = array(BLUE =>0x0a9ef3, RED => 0xea0a2f, GREEN => 0x336633);

$largestDiff = 0;
$closestColor = "";
foreach ($colors as $name => $rgbColor)
{
    if (!isset($smallestDiff)) {

        $smallestDiff = colorDiff($rgbColor,$rgb);
        $closestColor = $name;

    } else if (colorDiff($rgbColor,$rgb) < $smallestDiff)
    {
        $smallestDiff = colorDiff($rgbColor,$rgb);
        $closestColor = $name;
    }

}
return $closestColor;

}

function colorDiff($rgb1,$rgb2)
{
// do the math on each tuple

$red1 = hexdec(substr($rgb1,0,2));
$green1 = hexdec(substr($rgb1,2,2));
$blue1 = hexdec(substr($rgb1,4,2));

$red2 = hexdec(substr($rgb2,0,2));
$green2 = hexdec(substr($rgb2,2,2));
$blue2 = hexdec(substr($rgb2,4,2));

return abs($red1 - $red2) + abs($green1 - $green2) + abs($blue1 - $blue2) ;


}

使用绿色作为测试运行脚本(通常在循环中)

$color = '336633';
$closestmatch = getColor("0x".$color);

输出为红色!救命啊!

这是colorDIFF函数中的一个问题吗?

1 个答案:

答案 0 :(得分:1)

使用$closestmatch = getColor($color);代替$closestmatch = getColor("0x".$color);

$color = '336633';
echo getColor($color); // GREEN