【问题标题】:Algorithm to find border color of an image in PHP在PHP中查找图像边框颜色的算法
【发布时间】:2012-12-04 16:54:41
【问题描述】:

我正在尝试找到一种使用php从图像中获取边框颜色的方法

我曾尝试使用此代码,但此算法为我提供了任何图像中的所有颜色。

<?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('rmnp8.jpg', 10, 4); 
echo "<table>\n"; 
foreach($palette as $color) 
{ 
   echo "<tr><td style='background-color:#$color;width:2em;'>&nbsp;</td><td>#$color</td></tr>\n"; 
} 
echo "</table>\n";

另外,我正在尝试使用它来构建类似这些设计的设计。

【问题讨论】:

  • 有道理,你基本上是从网格中的图像中切出几个像素,并试图计算它们出现的频率。考虑一个长彩虹渐变的图像 - 您可能会在每个测试点获得独特的颜色。您将不得不降低您的粒度(例如,做更多的采样),或使用其他方法。

标签: php gd


【解决方案1】:

您获得图像中所有颜色的原因是因为您使用嵌套循环来迭代图像中的像素。相反,您应该使用两个顺序循环:一个检查水平边框,另一个检查垂直边框,因此您的循环代码将变成这样:

function checkColorAt(&$img, $x, $y, &$colors) {
    $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; 
    }
}


$colors = array();
for($x = 0; $x < $size[0]; $x += $granularity) 
{ 
    checkColorAt(&$img, $x, $0, &$colors);
    checkColorAt(&$img, $x, $size[1] - 1, &$colors);
}

for($y = 0; $y < $size[1]; $y += $granularity) 
{ 
    checkColorAt(&$img, $0, $y, &$colors);
    checkColorAt(&$img, $size[0] - 1, $y, &$colors);
}

【讨论】:

  • 我没有完全理解你,如果 $thisRGB 总是为空,我该如何使用你的代码?
  • @Othman 哈哈!很好,我混淆了变量名。数组名称应为$colors。我现在更正了代码。
猜你喜欢
  • 2013-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-25
  • 2014-08-03
  • 2017-01-26
相关资源
最近更新 更多