Saving two colour indexed (1bpp) PNG with Image Sharp

1.6k Views Asked by At

I'm using Image Sharp in an ASP.Net Core project and now need to prepare PNG images for a device that can only handle 2 colour indexed PNG images.

If I use the following code, then the images are saved as palleted 2 colour images, but the result is corrupt, looks to me that there is no pixel packing happening.

private void ConvertToMonoPng(Stream stream, string fileName)
{
    Image<Rgba32> image = Image.Load(fileName);

    var enc = new PngEncoder();
    enc.CompressionLevel = PngCompressionLevel.Level9;
    enc.ColorType = PngColorType.Palette;
    enc.BitDepth = PngBitDepth.Bit1;

    image.Save(stream, enc);
    image.Dispose();
}

The results are:

Source Image

Source image

Output Image

Output image

I know that the ImageSharp library doesn't currently support sub-byte packed pixels in memory, but since there does seem to be some support in the PNGEncoder, I'm hoping that saving monochrome PNG's is supported and I'm just doing something wrong.

1

There are 1 best solutions below

3
On BEST ANSWER

As of build 1.0.0-dev001921 this is now possible. I've added support for 1,2, and 4 bit encoding to accompany the existing 8 and 16 bit encoding.

You can install the package via the nightly MyGet feed using the following command.

PM> Install-Package SixLabors.ImageSharp -Version 1.0.0-dev001921 -Source 
https://www.myget.org/F/sixlabors/api/v3/index.json

Here's the output.

1 bit palette

1 bit palette

2 bit palette

2 bit palette

4 bit palette

4 bit palette

1 bit grayscale

1 bit grayscale

2 bit grayscale

2 bit grayscale

4 bit grayscale

4 bit grayscale