What I'm trying to do is convert an 8 bit image to a 16 bit image using php ImageMagick. With Imagick it's as easy as convert /location/image.jpg -colors 8 -depth 16 txt:-
. In the PHP docs it shows that you can do it using $imagick->setImageDepth(16);
but the problem is that it doesn't give you the 16 bit hex / rgb numbers.
Is there an advantage to using 16 bit when trying to extract colors from an image? If not then I'm wondering isn't the php function working?
Here is what I get from $mapColor->getColor()
:
Array
(
[r] => 51
[g] => 51
[b] => 51
[a] => 1
)
Array
Here is my code for getting colors:
// Create new instance
$imagick = new Imagick($image);
// Set number of colors
$numberColors = 6;
// Set colorspace
$colorSpace = Imagick::COLORSPACE_SRGB;
// Set tree depth
$treeDepth = 0;
// Set dither
$dither = false;
// Convert to 16 bit
$imagick->setImageDepth(16);
// Quantize image to number of colors
$imagick->quantizeImage($numberColors, $colorSpace, $treeDepth, $dither, false);
// Get Image Dimensions
$sizes = $imagick->getImageGeometry();
// Get image's histogram
$pixels = $imagick->getImageHistogram();
// Temp cache dimensions
$totalSize = $sizes['width'] * $sizes['height'];
// Loop through each pixel
foreach($pixels as $k => $v) {
// Get total number of color instances
$count = $v->getColorCount();
// Get colormap at pixel
$mapColor = $imagick->getImageColormapColor($k);
// Get colore
$rgbColor = $mapColor->getColor();
// Convert to RGB hex values
$red = str_pad(dechex($rgbColor['r']), 2, 0, STR_PAD_LEFT);
$green = str_pad(dechex($rgbColor['g']), 2, 0, STR_PAD_LEFT);
$blue = str_pad(dechex($rgbColor['b']), 2, 0, STR_PAD_LEFT);
// Set hexadecimal
$hex = $red.$green.$blue;
// Calculate color percentage
$percentage = (100 * $count) / $totalSize;
// Push colors into array
$colors[] = array(
'red' => $rgbColor['r'],
'green' => $rgbColor['g'],
'blue' => $rgbColor['b'],
'hex' => $hex,
'count' => $count,
'percentage' => $percentage,
);
}
print_r($colors);