C# – Generate image file with low bit depths

bitmapcimagingvb.net

bpp = bits per pixel, so 32bpp means 8/8/8/8 for R/G/B/A.

Like .NET has an enum for these "System.Drawing.Imaging.PixelFormat".

Now once I have a Bitmap or Image object with my graphics, how would I save it to a file / what format would I use?

What image file format (JPEG/GIF/PNG) supports low bit-depths like 16bpp or 8bpp (instead of the usual 32bpp or 24bpp)

Best Answer

I don't think the other's answering tested their code as GDI+ PNG does not support the Encoder.BitDepth EncoderParameter. In fact, the only Codec which does is TIFF.

You need to change your image's PixelFormat before saving in order to have any effect out the output. This won't always produce the PixelFormat you expect. See my post here for more information on which PixelFormats turn into what.

As for PixelFormat conversions, something like the following will work:

private Bitmap ChangePixelFormat(Bitmap inputImage, PixelFormat newFormat)
{
  Bitmap bmp = new Bitmap(inputImage.Width, inputImage.Height, newFormat);
  using (Graphics g = Graphics.FromImage(bmp))
  {
    g.DrawImage(inputImage, 0, 0);
  }
  return bmp;
}

Unfortunately, these conversions can produce some really bad output. This is especially true in the case where you are performing a lossy conversion (high bit depth to lower).

Related Topic