ccpalettes / gd-indexed-color-converter

Convert an image to indexed color mode.
http://ccpalettes.github.io/gd-indexed-color-converter/
MIT License
12 stars 7 forks source link

How to save image as monochrome (black/white, 1 Bit colormap)? #1

Open igittigitt opened 5 years ago

igittigitt commented 5 years ago

I use the following code with your lib to achieve a monochrome image with just black and white pixels in it (1 Bit colordepth):

$converter = new GDIndexedColorConverter();
$palette = array(
    array(0, 0, 0),
    array(255, 255, 255),
);
$new_image = $converter->convertToIndexedColor($image, $palette, 0.8);
imagepng($new_image, 'bwimage.png', 6);

But the resulting imagefile is written as RGB with 8-Bit colordepth:

root@server /tmp # file bwimage.png
bwimage.png: PNG image data, 76 x 96, 8-bit/color RGB, non-interlaced

I've tried to add filters, like found on the Internet, but they seem to have no effect on the output format:

$converter = new GDIndexedColorConverter();
$palette = array(
    array(0, 0, 0),
    array(255, 255, 255),
);
$new_image = $converter->convertToIndexedColor($image, $palette, 0.8);
imagefilter($new_image, IMG_FILTER_GRAYSCALE);
imagefilter($new_image, IMG_FILTER_CONTRAST, -1000);
imagepng($new_image, 'bwimage.png', 6);
igittigitt commented 5 years ago

An acceptable solution for me is this:

$bw_img = $converter->convertToIndexedColor($img, $palette, 0.8);
imagefilter($bw_img, IMG_FILTER_NEGATE);
imagetruecolortopalette($bw_img, true, 2);
imagecolorset($bw_img, 0, 255, 255, 255);
imagecolorset($bw_img, 1, 0, 0, 0);