How can I force a pre-defined colour palette on a image using PHP?
I'm looking to take an image and reduce the colour palette to a pre-set palette. I want to try pure black and white, 16 colours, 64 colours, and so on.
I can't use imagetruecolortopalette()
because it builds the palette based on the image colours, whereas I want to use a pre-defined palette. I also can't just make it grayscale and then colourize it, either, because that would mean I lose all the original colours and the resulting image would still only be o开发者_C百科ne colour.
I saw this function on the php function comments the other day which would do the trick for you. All you have to do is create an array of the colors you want in your "new" image and pass it the old one.
$arr = array('#000000', '#990000', '#00FFFF', '#FFFFDD');
colorize ($img, $arr);
<?php
function colorize($imgdata, $palette)
{
imageTrueColorToPalette($imgdata,false,0xFF);
$l = count($palette)-1;
$i = imagecolorstotal($imgdata);
while ($i--)
{
list($r,$g,$b) = array_values(imageColorsForIndex($imgdata,$i));
$grayscale = ($r*.3 + $g*.59 +$b*.11) / 0xFF;
$pos = $l*$grayscale;
$perc = $pos-floor($pos);
$tbase = str_replace("#", '', $palette[$pos]);
$baseR = hexdec(substr($tbase,0,2));
$baseG = hexdec(substr($tbase,2,2));
$baseB = hexdec(substr($tbase,4,2));
$tmix = str_replace("#", '', $palette[$pos+1]);
$mixR = hexdec(substr($tmix,0,2));
$mixG = hexdec(substr($tmix,2,2));
$mixB = hexdec(substr($tmix,4,2));
$resR = $baseR+($mixR-$baseR)*$perc;
$resG = $baseG+($mixG-$baseG)*$perc;
$resB = $baseB+($mixB-$baseB)*$perc;
imagecolorset($imgdata, $i, $resR, $resG, $resB);
}
}
?>
精彩评论