Get the color palette for an image using PHP
Thursday, January 5, 2012 EST
by: Eric Potvin
Tags:php
Have you every wonder what kind of colors you should get to match your logo for your website? Here's a very simple script that generates a color palette for an image using the PHP GD library. This will help you find out which colors you can use to improve quality of your site.
Requirement:
The script:
function detectColors($image, $num, $level = 5) {
$level = (int)$level;
$palette = array();
$size = getimagesize($image);
if(!$size) {
return FALSE;
}
switch($size['mime']) {
case 'image/jpeg':
$img = imagecreatefromjpeg($image);
break;
case 'image/png':
$img = imagecreatefrompng($image);
break;
case 'image/gif':
$img = imagecreatefromgif($image);
break;
default:
return FALSE;
}
if(!$img) {
return FALSE;
}
for($i = 0; $i < $size[0]; $i += $level) {
for($j = 0; $j < $size[1]; $j += $level) {
$thisColor = imagecolorat($img, $i, $j);
$rgb = imagecolorsforindex($img, $thisColor);
$color = sprintf('%02X%02X%02X', (round(round(($rgb['red'] / 0x33)) * 0x33)), round(round(($rgb['green'] / 0x33)) * 0x33), round(round(($rgb['blue'] / 0x33)) * 0x33));
$palette[$color] = isset($palette[$color]) ? ++$palette[$color] : 1;
}
}
arsort($palette);
return array_slice(array_keys($palette), 0, $num);
}
$img = 'icon.png';
$palette = detectColors($img, 6, 1);
echo '<img src="' . $img . '" />';
echo '<table>';
foreach($palette as $color) {
echo '<tr><td style="background:#' . $color . '; width:36px;"></td><td>#' . $color . '</td></tr>';
}
echo '</table>';
Example:
Will output:
| | #FFFFFF |
| | #000000 |
| | #CCCCCC |
| | #FFCC99 |
| | #FF6600 |
| | #FF9900 |
Link to this Article
To link directly to this article from your web site, use one of the following snippets below.
Get the color palette for an image using PHP | Book Of Zeus<a href="http://www.bookofzeus.com/articles/get-the-color-palette-for-an-image-using-php/" title="Get the color palette for an image using PHP">Get the color palette for an image using PHP | Book Of Zeus</a>
Short URL:
Get the color palette for an image using PHP | Book Of Zeus<a href="http://s.bookofzeus.com/tOsl5" title="Get the color palette for an image using PHP Short URL">Get the color palette for an image using PHP | Book Of Zeus</a>