//This article has been translated by www.blue1000.com , the original address is http://codebetter.com/blogs/brendan.tompkins/archive/2004/01/26/6103.aspx
//Respect the fruits of others' labor, please indicate the source when reprinting.
GDI+ is often used when writing programs. It can save a dark 32 bpp image as a gif file, and the process is relatively simple. And before saving this gif image using the CreateThumnailImage method, you can also adjust its size.
Commonly used codes:
The above code can complete the drawing and saving of gif files, but you will soon find a problem: the generated thumbnail The image quality of the .gif file is far below our expectations.
Effect picture:
The low-quality, grainy image shown above also requires "color quantization" processing (palettization). This happens because GDI+ uses 256 colors by default, without considering the actual color of the image itself.
After that, we tried to create our own "palette", but the results were even worse :). A good "color quantization" algorithm should consider filling the space between two pixel particles with a transition color that is similar to the color of the two pixels, providing more visible color space.
This is the "Octree" algorithm. The “Octree“ algorithm allows us to plug in our own algorithm to quantize our images.
Here are two articles from Microsoft that may be helpful to us: KB 319061 and Optimizing Color Quantization for ASP.NET Images (by Morgan Skinner, Microsoft). Morgan Skinner provides a good "Octree" algorithm code, which you can download for reference.
Using OctreeQuantizer is easy:
System.Drawing.Bitmap b = new System.Drawing.Bitmap(“c:\original_image.gif“);
System.Drawing.Image thmbnail = b.GetThumbnailImage(100,75,null,new IntPtr());
OctreeQuantizer quantizer = new OctreeQuantizer ( 255 , 8 ) ;
using (Bitmap quantized = quantizer.Quantize (thmbnail) )
{
quantized.Save(“c:\thumnail.gif“, System.Drawing.Imaging.ImageFormat.Gif);
}
OctreeQuantizer grayquantizer = new GrayscaleQuantizer ( );
using ( Bitmap quantized = grayquantizer.Quantize ( thmbnail ) )
{
quantized.Save(“c:\thumnail.gif“, System.Drawing.Imaging.ImageFormat.Gif);
}
The effect picture is as follows (is it much more beautiful?):