使用php进行图像颜色检测

时间:2011-11-04 20:51:51

标签: php colors

我使用以下代码来检测图像颜色:

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);
}

这里已经介绍了这个代码 Detect "overall average" color of the picture
但是,此代码不适用于分辨率为2500px的图像更大! 有什么问题?
非常感谢

2 个答案:

答案 0 :(得分:2)

假设图像足够大并且包含所有可能的颜色,您可能会创建一个包含多达1670万个元素的数组。即使是2500x2500的图像也可能拥有625万种独特的颜色。

更简单的解决方法是将图像调整为单个1x1像素,然后读出该像素的颜色..

答案 1 :(得分:0)

你可以分割图像,然后检查它,我认为它会起作用。

相关问题