Skip to content

Instantly share code, notes, and snippets.

@cesarmiquel
Created December 23, 2013 05:15
Show Gist options
  • Save cesarmiquel/8091999 to your computer and use it in GitHub Desktop.
Save cesarmiquel/8091999 to your computer and use it in GitHub Desktop.
Create a color palette from an image.
<?php
$img = imagecreatefrompng ( '/tmp/image.png' );
$palette = build_palette($img, 20, 20);
$unique_colors = array();
foreach($palette as $row) {
foreach($row as $col) {
$rgb = sprintf('%02x%02x%02x', $col['r'], $col['g'], $col['b']);
if (!isset($unique_colors[$rgb])) {
$unique_colors[$rgb] = $rgb;
}
}
}
sort($unique_colors);
echo '<div class="container">';
foreach($unique_colors as $index => $color) {
echo '<div class="box" style="background-color:#' . $color . '"></div>';
}
echo'</div>';
// The function takes in an image resource (the result from one
// of the GD imagecreate... functions) as well as a width and
// height for the size of colour palette you wish to create.
// This defaults to a 3x3, 9 block palette.
function build_palette($img_resource, $palette_w = 3, $palette_h = 3) {
$width = imagesx($img_resource);
$height = imagesy($img_resource);
// Calculate the width and height of each palette block
// based upon the size of the input image and the number
// of blocks.
$block_w = round($width / $palette_w);
$block_h = round($height / $palette_h);
for($y = 0; $y < $palette_h; $y++) {
for($x = 0; $x < $palette_w; $x++) {
// Calculate where to take an image sample from the soruce image.
$block_start_x = ($x * $block_w);
$block_start_y = ($y * $block_h);
// Create a blank 1x1 image into which we will copy
// the image sample.
$block = imagecreatetruecolor(1, 1);
imagecopyresampled($block, $img_resource, 0, 0, $block_start_x, $block_start_y, 1, 1, $block_w, $block_h);
// Convert the block to a palette image of just one colour.
imagetruecolortopalette($block, true, 1);
// Find the RGB value of the block's colour and save it
// to an array.
$colour_index = imagecolorat($block, 0, 0);
$rgb = imagecolorsforindex($block, $colour_index);
$colour_array[$x][$y]['r'] = $rgb['red'];
$colour_array[$x][$y]['g'] = $rgb['green'];
$colour_array[$x][$y]['b'] = $rgb['blue'];
imagedestroy($block);
}
}
imagedestroy($img_resource);
return $colour_array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment