27

How can I detect the top 2 colors of an Image in PHP?

for example I have this image:

enter image description here

This function/process will return: 0000FF or blue and FFFF00 or YELLOW

Thanks

Tech4Wilco
  • 6,740
  • 5
  • 46
  • 81

2 Answers2

24

Here's a script that will give you the list:

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>';
rcs20
  • 595
  • 9
  • 27
  • 4
    I would optimize this by replacing the Switch Case with `$img = @imagecreatefromstring(file_get_contents($image));` so you can process different image types efficiently... – Andres Feb 08 '12 at 16:01
  • This looks like you're basically getting the colour value of every pixel in a loop. I think maybe grabbing the image histogram might be way more efficient if IMagick is available. http://php.net/manual/en/imagick.getimagehistogram.php – GordonM Nov 23 '15 at 11:45
  • why do i need to round with 0X33? (round(round(($rgb['red'] / 0x33)) * 0x33)) – Michael Mulik Mar 31 '22 at 09:46
0

If you are OK to call an external utility, Imagemagick can generate a histogram for you. It's probably going to be much faster than a PHP implementation.

Basically, this command gives you a list of colours, sorted by most dominant first:

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

You might want to map the image to a fixed palette first ("Round off" the colours). This is what I use:

convert 'https://i.stack.imgur.com/J2txV.png' -modulate 100,200,100 -remap 'https://i.stack.imgur.com/GvTqB.png' -format %c histogram:info:-|sort -r
troelskn
  • 115,121
  • 27
  • 131
  • 155