C# Why Bitmap.Save ignores PixelFormat of Bitmap?

xZ6a33YaYEfmv picture xZ6a33YaYEfmv · Jan 13, 2011 · Viewed 14.1k times · Source

I need to process and save images in their original bpp (1 - for BnW, 8 - for gray, 24 - color). After processing I always have 24bpp (due to processing with Aforge.Net). I pass original bpp to saving function and I'm using the next code for saving:

private static Bitmap changePixelFormat(Bitmap input, PixelFormat format)
    {
        Bitmap retval = new Bitmap(input.Width, input.Height, format);
        retval.SetResolution(input.HorizontalResolution, input.VerticalResolution);
        Graphics g = Graphics.FromImage(retval);
        g.DrawImage(input, 0, 0);
        g.Dispose();
        return retval;
    }

When I pass:

PixelFormat.Format8bppIndexed

I'm getting an exception: "Graphics object can't create image in indexed pixel format" in the line:

Graphics g = Graphics.FromImage(retval);

I've tried the next code:

Bitmap s = new Bitmap("gray.jpg");
        Bitmap NewPicture = s.Clone(new Rectangle(0, 0, s.Width, s.Height),                   PixelFormat.Format8bppIndexed);

After this "NewImage" has PixelFormat 8bppIndexed, but when I'm saving NewImage:

NewPicture.Save("hello.jpg", ImageFormat.Jpeg);

hello.jpg has 24bpp.

I need to keep bpp and image format of original image.

Why Bitmap.Save ignores PixelFormat of Bitmap?

=======================================================

Thanks guys, I've found a solution: http://freeimage.sourceforge.net/license.html

With help of this free library it is possible to save images (especially JPEG ) to Grayscale 8-bit.

Answer

Cody Gray picture Cody Gray · Jan 13, 2011

I'm almost positive that the JPEG image format doesn't support indexed images. So even though you created the image specifying PixelFormat.Format8bppIndexed, GDI+ is converting it to a different format when you attempt to save it as a JPEG. In this case, you've already determined that's 24 bpp.

Instead, you need to save the image as a BMP or GIF. For example:

NewPicture.Save("hello.jpg", ImageFormat.Bmp);

See the table of image file formats supporting indexed color here on Wikipedia.