问题
My goal
I have an existing PNG. It currently has anti-aliasing, or in other words, shades of gray. I want the image to be 1 bit, or in other words, only using the colors black and white. My aim is to do this with PHP GD. I have to do this with an existing image, and can not create the image from scratch using imagecreatetruecolor.
What I'm trying
The function I've found that seems best for the job is imagetruecolortopalette http://php.net/manual/en/function.imagetruecolortopalette.php
Here is a simple version of what I'm trying to do
$user_design = base64_decode($_POST['input']);
$design_file = fopen('path/filename.png', 'w') or die("Unable to open file!");
imagetruecolortopalette($design_file, false, 1);
fwrite($design_file, $user_design);
fclose($design_file);
With this being the key line. The 1 being the "maximum number of colors that should be retained in the palette."
imagetruecolortopalette($design_file, false, 1);
Behavior I'm getting
The image appears unchanged. I'm not sure if I'm using PHP GD correctly, or if this function doesn't do what I think it does.
Other ideas
These also seem promising.
imagecolordeallocate seems like I may be able to use it to deallocate colors, but not sure how to do this without calling it 254 times.
http://php.net/manual/en/function.imagecolordeallocate.php
imagecolorset seems like I may be able to use it to set the palette, but I'm not sure how to do this for existing images.
http://php.net/manual/en/function.imagecolorset.php
Mostly I suspect imagetruecolortopallette is the best bet, but any and all ideas welcome.
回答1:
$im = imagecreatefromstring($user_design);
imagefilter($im, IMG_FILTER_GRAYSCALE);
imagefilter($im, IMG_FILTER_CONTRAST, -1000);
imagepng($im, 'path/filename.png');
imagedestroy($im);
How do you convert an image to black and white in PHP
来源:https://stackoverflow.com/questions/31342505/how-to-use-php-gd-to-create-1-bit-bitmaps-black-and-white-only-no-gray