如何使用PHP GD创建1位位图(只有黑白,没有灰色)

How to use PHP GD to create 1 bit bitmaps (black and white only, no gray)

我的目标

我有一个现有的 PNG。它目前具有抗锯齿功能,或者换句话说,具有灰色阴影。我希望图像为 1 位,或者换句话说,只使用黑色和白色。我的目标是用 PHP GD 来做到这一点。我必须使用现有图像执行此操作,并且无法使用 imagecreatetruecolor 从头开始​​创建图像。

我正在尝试什么

我发现最适合这项工作的函数是 imagetruecolortopalette http://php.net/manual/en/function.imagetruecolortopalette.php

这是我正在尝试做的一个简单版本

$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);

这是关键线。 1 是 "maximum number of colors that should be retained in the palette."

imagetruecolortopalette($design_file, false, 1);

我得到的行为

图像看起来没有变化。我不确定我是否正确地使用了 PHP GD,或者这个函数是否不符合我的预期。

其他想法

这些似乎也很有希望。

imagecolordeallocate 似乎我可以用它来取消分配颜色,但不知道如何在不调用它 254 次的情况下做到这一点。

http://php.net/manual/en/function.imagecolordeallocate.php

imagecolorset 似乎我可以使用它来设置调色板,但我不确定如何对现有图像执行此操作。

http://php.net/manual/en/function.imagecolorset.php

大多数情况下,我怀疑 imagetruecolortopallette 是最好的选择,但欢迎任何想法。

$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