hi i wanna create a css-file for my site based on a image. now i need a function that can grab the 4-6 most common colors from any given image - something like colorhunter.com . i have like ~100 pictures, and i dont wanna run them all thru colorhunter had anyone an idea how this is done???
Here you go. Just note that this function is slow and memory consuming. <?php function imagemostcommoncolor($source, $num_colors = 10) { if (!$image = @imagecreatefromjpeg($source)) { trigger_error("Unable to open image {$source}", E_USER_WARNING); return false; } $width = imagesx($image); $height = imagesy($image); $colors = array(); for ($x = 0; $x < $width; $x++) { for ($y = 0; $y < $height; $y++) { $index = imagecolorat($image, $x, $y); $rgb = imagecolorsforindex($image, $index); $hexcolor = rgbhex($rgb['red'], $rgb['green'], $rgb['blue']); if (isset($colors[$hexcolor])) { $colors[$hexcolor]++; } else { $colors[$hexcolor] = 1; } } } arsort($colors); array_splice($colors, $num_colors); return array_keys($colors); } function rgbhex($red, $green, $blue) { return sprintf('%02X%02X%02X', $red, $green, $blue); } PHP: It returns the 10 most common colors of the image (Unless you specify another amount in the second, optional parameter). Usage example: $colors = imagemostcommoncolor('path/to/image.jpg'); foreach ($colors AS $color) { echo '<span style="color: #', $color, ';">', $color, "</span><br />\n"; } PHP:
hm thanks, i had something like this in mind as well (get the color for each single pixel...), guess there is no "used colors" palette you could just read out for gif or png file?