Skip to content

Instantly share code, notes, and snippets.

@faffyman
Created October 5, 2012 07:51
Show Gist options
  • Save faffyman/3838632 to your computer and use it in GitHub Desktop.
Save faffyman/3838632 to your computer and use it in GitHub Desktop.
Build a colorProfile from an image with Imagick
/**
* Generate a Color Palette
* Using Imagick to quantize the image
* (http://www.php.net/manual/en/class.imagick.php)
*
* ASSUMPTION - your image directory has suitable permission levels to allow
* your script to edit/copy/create files.
**/
// How many colors will we reduce the image to?
define('NUM_COLORS',16);
// define pathways
define('IMG_DIR', path_to_img_dir_on_your_system) ;
// Uses Imagick - so make sure it exists
if (class_exists('Imagick')) {
// Make a temporary copy of the image
exec('cp ' . IMG_DIR . '/'. $sImage.' ' . IMG_DIR .'/TEMP-'.$sImage );
// First reduce the colors by quantizing the temporary image
$oImagick = new Imagick(IMG_DIR .'/TEMP-'.$sImage );
$colorSpace = 1;
$treeDepth = 0;
$dither = 0;
$measureError = 0;
$oImagick->quantizeImage(NUM_COLORS, $colorSpace,$treeDepth,$dither,$measureError);
// Now we have reduced the image to NUM_COLORS - what are those colors ?
$nColors = $oImagick->getImageColors();
for ($i=0;$i<$nColors;$i++) {
$oImPixel = $oImagick->getImageColormapColor($i);
$aColor = $oImPixel->getColor();
// Convert to RGB hex values
// --------------------------
$r = str_pad(dechex($aColor['r']),2,0,STR_PAD_LEFT);
$g = str_pad(dechex($aColor['g']),2,0,STR_PAD_LEFT);
$b = str_pad(dechex($aColor['b']),2,0,STR_PAD_LEFT);
// Create a little block of this color
// -------------------------------------
// echo 'dec to hex - '.$r.$g.$b;
// echo '<div style="width:50px; height:22px;background-color:#'.$r.$g.$b.';">&nbsp; </div>';
// echo 'RGB %';
// echo '<div style="width:50px; height:22px;background-color:'.$oImPixel->getColorAsString().'">&nbsp; </div>';
// echo '<br /> - - - - - - '.$oImPixel->getColorAsString();
} // end for each color
// Delete the temporary image
exec('rm '. IMG_DIR .'/TEMP-'.$sImage );
} // end If imagick exists
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment