C# Why Bitmap.Save ignores PixelFormat of Bitmap?

陌路散爱 提交于 2019-12-01 07:35:39

Here is the code that will convert a Bitmap to 1bpp/8bpp bitmap. 1bpp/8bpp in C#.

In your changePixelFormat method you can check what fixel format it needs to be converted to, then if it's 1bpp or 8 bpp then use code from link and for all other formats use your code.

Graphics.FromImage documentation has remarks:

If the image has an indexed pixel format, this method throws an exception with the message, "A Graphics object cannot be created from an image that has an indexed pixel format." The indexed pixel formats are shown in the following list.

Format1bppIndexed

Format4bppIndexed

Format8bppIndexed

NEW PART:

This is what i found after short googling:

8bpp greyscale images and 8bpp jpg is not supported with gdiplus version 1.0. There is a new version of gdiplus in Windows 7 that supports greyscale images and more enhanced codec support.

8bpp indexed jpeg images are supported with Microsoft's WIC API.

You can try it yourself by downloading the WIC explorer from Microsoft's download site.

GDI+ 8 bit load/save bug

Standard JPEG only supports 24-bit image.

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.

Brent Matzelle

If you're looking for a true 8-bit grayscale bitmap image then I made a detailed StackOverflow post about it. It will work on any operating system (Windows/Mac/Linux), not just Windows 7. I hope it helps.

Use Graphics class for non indexed image. UseBitmap.LockBits and Bitmap.UnlockBits when processing indexed images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!