Reputation: 2157
I have found a wonderful function to display a palette of the colors in an image. My only problem is I need to be able to support png and gif files as well. Not sure if it is an easy fix or not. Appreciate any help or direction.
function colorPalette($imageFile, $numColors= 5, $granularity = 5) {
$granularity = max(1, abs((int)$granularity));
$colors = array();
$size = @getimagesize($imageFile);
if($size === false) {
user_error("Unable to get image size data");
return false;
}
$imgData = file_get_contents($imageFile);
$img = @imagecreatefromstring($imgData);
unset($imgData);
if(!$img) {
user_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);
}
EDIT
I changed the code above to reflect what I was trying to accomplish.
This is how the function can be used
$palette = colorPalette('image_path_here', 5);
echo "<table>\n";
foreach($palette as $color) {
echo "<tr><td style='background-color:#$color;width:2em;'> </td><td>#$color</td></tr>\n";
}
echo "</table>\n";
credit for the function goes here: http://board.phpbuilder.com/showthread.php?10355107-How-to-get-color-palette-from-images-using-PHP
Upvotes: 1
Views: 760
Reputation: 180045
imagecreatefromjpeg has equivalents for other formats, imagecreatefrompng and imagecreatefromgif. You can look at the file extension and use the appropriate one.
Upvotes: 2