使用PHP检测图像的颜色

Tec*_*lco 25 php colors detection

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

例如,我有这个图像:

在此输入图像描述

此功能/过程将返回:0000FF蓝色FFFF00黄色

谢谢

rcs*_*s20 21

这是一个给你列表的脚本:

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>';
Run Code Online (Sandbox Code Playgroud)

  • 你基本上只是复制了我所参考的页面的代码.要走的路...... (5认同)
  • 我会通过用`$ img = @imagecreatefromstring(file_get_contents($ image))替换Switch Case来优化这个;`这样你就可以有效地处理不同的图像类型...... (4认同)
  • 我添加了修复,但是你是对的 (3认同)