Posted By

uberdragon on 10/25/11


Tagged


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

IMPGTX
Net-Freak
canberkol


colorPalette Function returns all colors in an image


 / Published in: PHP
 

This gives you an array whose values are higher for how often that color has been used.

  1. <?php
  2. function colorPalette($imageFile, $numColors, $granularity = 5)
  3. {
  4. $granularity = max(1, abs((int)$granularity));
  5. $colors = array();
  6. $size = @getimagesize($imageFile);
  7. if($size === false)
  8. {
  9. user_error("Unable to get image size data");
  10. return false;
  11. }
  12. $img = @imagecreatefromjpeg($imageFile);
  13. if(!$img)
  14. {
  15. user_error("Unable to open image file");
  16. return false;
  17. }
  18. for($x = 0; $x < $size[0]; $x += $granularity)
  19. {
  20. for($y = 0; $y < $size[1]; $y += $granularity)
  21. {
  22. $thisColor = imagecolorat($img, $x, $y);
  23. $rgb = imagecolorsforindex($img, $thisColor);
  24. $red = round(round(($rgb['red'] / 0x33)) * 0x33);
  25. $green = round(round(($rgb['green'] / 0x33)) * 0x33);
  26. $blue = round(round(($rgb['blue'] / 0x33)) * 0x33);
  27. $thisRGB = sprintf('%02X%02X%02X', $red, $green, $blue);
  28. if(array_key_exists($thisRGB, $colors))
  29. {
  30. $colors[$thisRGB]++;
  31. }
  32. else
  33. {
  34. $colors[$thisRGB] = 1;
  35. }
  36. }
  37. }
  38. arsort($colors);
  39. return array_slice(array_keys($colors), 0, $numColors);
  40. }
  41. // sample usage:
  42. $palette = colorPalette('rmnp8.jpg', 10, 4);
  43. echo "<table>\n";
  44. foreach($palette as $color)
  45. {
  46. echo "<tr><td style='background-color:#$color;width:2em;'>&nbsp;</td><td>#$color</td></tr>\n";
  47. }
  48. echo "</table>\n";
  49.  
  50. ?>

Report this snippet  

You need to login to post a comment.