【问题标题】:Detecting colors for an Image using PHP使用 PHP 检测图像的颜色
【发布时间】:2011-12-05 09:13:27
【问题描述】:

如何在 PHP 中检测图像的前 2 种颜色?

例如我有这张图片:

此函数/进程将返回:0000FFblueFFFF00YELLOW

谢谢

【问题讨论】:

标签: php colors detection


【解决方案1】:

这里有一个脚本可以为您提供列表:

function detectColors($image, $num, $level = 5) {
  $level = (int)$level;
  $palette = array();
  $size = getimagesize($image);
  if(!$size) {
    return FALSE;
  }
  switch($size['mime']) {
    case 'image/jpeg':
      $img = imagecreatefromjpeg($image);
      break;
    case 'image/png':
      $img = imagecreatefrompng($image);
      break;
    case 'image/gif':
      $img = imagecreatefromgif($image);
      break;
    default:
      return FALSE;
  }
  if(!$img) {
    return FALSE;
  }
  for($i = 0; $i < $size[0]; $i += $level) {
    for($j = 0; $j < $size[1]; $j += $level) {
      $thisColor = imagecolorat($img, $i, $j);
      $rgb = imagecolorsforindex($img, $thisColor); 
      $color = sprintf('%02X%02X%02X', (round(round(($rgb['red'] / 0x33)) * 0x33)), round(round(($rgb['green'] / 0x33)) * 0x33), round(round(($rgb['blue'] / 0x33)) * 0x33));
      $palette[$color] = isset($palette[$color]) ? ++$palette[$color] : 1;  
    }
  }
  arsort($palette);
  return array_slice(array_keys($palette), 0, $num);
}

$img = 'icon.png';
$palette = detectColors($img, 6, 1);
echo '<img src="' . $img . '" />';
echo '<table>'; 
foreach($palette as $color) { 
  echo '<tr><td style="background:#' . $color . '; width:36px;"></td><td>#' . $color . '</td></tr>';   
} 
echo '</table>';

【讨论】:

  • 我会通过将 Switch Case 替换为 $img = @imagecreatefromstring(file_get_contents($image)); 来优化这一点,这样您就可以有效地处理不同的图像类型...
  • 这看起来你基本上是在循环中获取每个像素的颜色值。我认为如果 IMagick 可用,抓取图像直方图可能会更有效。 php.net/manual/en/imagick.getimagehistogram.php
【解决方案2】:

如果您可以调用外部实用程序,Imagemagick 可以为您生成直方图。它可能会比 PHP 实现快得多。

基本上,此命令会为您提供一个颜色列表,按最显着的顺序排列:

convert 'http://i.stack.imgur.com/J2txV.png' -format %c histogram:info:-|sort -r

您可能希望首先将图像映射到固定调色板(“四舍五入”颜色)。这是我使用的:

convert 'http://i.stack.imgur.com/J2txV.png' -modulate 100,200,100 -remap 'http://i.stack.imgur.com/GvTqB.png' -format %c histogram:info:-|sort -r

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-16
    • 2011-01-17
    • 2013-01-26
    • 2019-05-12
    • 2012-08-27
    • 2021-08-17
    • 2016-08-29
    • 1970-01-01
    相关资源
    最近更新 更多