Created
February 26, 2013 14:14
-
-
Save yuxel/5038698 to your computer and use it in GitHub Desktop.
get image color palette
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Sonsuzdongu; | |
class Image | |
{ | |
private $colors = array( | |
"black" => array(0, 0, 0), | |
"green" => array(0, 128, 0), | |
"green:x" => array(120, 150, 70), | |
"green:xxx" => array(0, 255, 0), | |
"silver" => array(192, 192, 192), | |
"gray" => array(128, 0, 128), | |
"gray:x" => array(160, 160, 160), | |
"gray:xx" => array(110, 120, 120), | |
"white" => array(255, 255, 255), | |
"yellow" => array(255, 255, 0), | |
"yellow:xxx" => array(128, 128, 0), | |
"red" => array(255, 30, 30), | |
"red:x" => array(215, 90, 110), | |
"red:xx" => array(128, 0, 0), | |
"brown" => array(200, 150, 80), | |
"brown:x" => array(200, 190, 180), | |
"orange" => array(230, 120, 50), | |
"blue" => array(0, 0, 255), | |
"blue:x" => array(70, 190, 190), | |
"blue:xx" => array(0, 255, 255), | |
"blue:xxx" => array(0, 128, 128), | |
"blue:xxxx" => array(0, 0, 128), | |
"purple" => array(128, 0, 128), | |
"purple:xx" => array(255, 0, 255), | |
); | |
private function distancel2(array $color1, array $color2) | |
{ | |
return sqrt(pow($color1[0] - $color2[0], 2) + | |
pow($color1[1] - $color2[1], 2) + | |
pow($color1[2] - $color2[2], 2)); | |
} | |
private function getClosest($val) | |
{ | |
$distances = array(); | |
if (!is_array($val)) { | |
return ""; | |
} | |
foreach ($this->colors as $name => $c) { | |
$distances[$name] = $this->distancel2($c, $val); | |
} | |
$mincolor = ""; | |
$minval = pow(2, 30); /*big value*/ | |
foreach ($distances as $k => $v) { | |
if ($v < $minval) { | |
$minval = $v; | |
$mincolor = $k; | |
} | |
} | |
return current(explode(":", $mincolor)); | |
} | |
public function getImageColors($img) | |
{ | |
$img = \ImageCreateFromJpeg($img); | |
$imgw = imagesx($img); | |
$imgh = imagesy($img); | |
$im = imagecreatetruecolor(150, 150); | |
imagecopyresized($im, $img, 0, 0, 0, 0, 150, 150, $imgw, $imgh); | |
$imgw = imagesx($im); | |
$imgh = imagesy($im); | |
$n = $imgw*$imgh; | |
$colors = array(); | |
for ($i=0; $i<$imgw; $i++) { | |
for ($j=0; $j<$imgh; $j++) { | |
$rgb = ImageColorAt($im, $i, $j); | |
$r = ($rgb >> 16) & 0xFF; | |
$g = ($rgb >> 8) & 0xFF; | |
$b = $rgb & 0xFF; | |
$c = $this->getClosest(array($r, $g, $b)); | |
if ($c == "white") continue; | |
if (isset($colors[$c])) { | |
$colors[$c]++; | |
} else { | |
$colors[$c] = 1; | |
} | |
} | |
} | |
arsort($colors); | |
return $colors; | |
} | |
} | |
$x = new Image; | |
print_r($x->getImageColors("http://www.stilsos.com/temp/resized/product-310863-x2.jpg")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment