PHP Palette Builder

Using simple PHP image manipulation it is possible to analyse the colours represented in an image and produce a colour palette of web-safe hex colours. Select one of the image thumbnails below to see the palette generation in action.

#FF0000
#FF3300
#CC0000
#330000
#660000
#FF6600
#990000
#333300
#FF6633
#CC3300
#CCCCCC
#666633

 

<?php

  function colorPalette($imageFile, $numColors, $granularity=5){
    $granularity = max(1, abs((int)$granularity));
    $colors = array();
    $size = @getimagesize($imageFile);
    if($size === false){
      trigger_error("Unable to get image size data");
      return false;
    }
    $img = @imagecreatefromstring(file_get_contents($imageFile));
    if(!$img){
      trigger_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);
  }
  
  $img = "images/01.jpg";
  $lvl = 12;
  
  $palette = colorPalette($img, $lvl);
  
  foreach($palette as $color){ 
    echo "<div class='color' style='background-color:#$color;'>#$color</div>";
  }
  
?>

 

Inspiration (and the seeds of the code) were taken from https://www.neowin.net/forum/topic/936848-php-get-colour-from-image/