Losing image quality in c# using Image class (reduces amount of colors)

[亡魂溺海] 提交于 2019-12-04 10:13:25

System.Drawing has poor support for 8-bit images. When converting from 24 or 32-bit images to 8-bit; it'll always use a fixed default color palette. That default color palette only contains 16 shades of grey, the other entries are various colors.

Do you have the same problem when saving as '.bmp'? If yes, then the conversion to the 8-bit format already happened earlier, you'll have to figure out where your program does that and fix the issue there. If it's only the tiff encoder that converts to 8-bit, you'll have to do the 8-bit conversion in a separate step first. Create an 8-bit image, fill Image.Palette with a gray-scale palette, and then copy the bitmap data over.

But System.Drawing has poor support for 8-bit images, and several methods (e.g. SetPixel) will just throw InvalidOperationException when dealing with such images. You will probably have to use unsafe code (with LockBits etc.) to copy the bitmap data. If I were you, I'd look if there are alternative graphics libraries you could use.

I had issues with using the .NET libraries to find good balances of image quality and size. I gave up rolling my own and tried out a few imaging libraries. I found http://imageresizing.net/ to produce consistently good results, much better than I was able to do.

Just throwing that out there as a plan B in case the roll your own method doesn't wind up working well on a consistent basis for you.

endofzero

Image.Save by default uses a quality setting of 75%. You could try using one of the other overloads of the method that allows you to specify quality setting parameters. See this question.

Only one suggestion really....when loading the Image you use new Bitmap(fileName)... Rather than using Bitmap have you considered using

Image tiffImage = Image.FromFile(tiffFileName, true);

The true tells it to use "embedded color management", and using Image instead of Bitmap avoids any image casting that might be occurring behind the scenes.

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