One of the features notably lacking in GDI+ is the ability to optimize color reduction for images. This is particularly important if you want to export optimized GIF images.

This example shows you how to use ImageGlue to color reduce a GIF image using an adaptive palette and then export the result. Using this combination you get the LZW compression of GDI+ and the sophisticated color reduction capabilities of ImageGlue.

Drawing our Image

We create our ImageGlue canvas and draw our image onto it.

[C#] Canvas canvas = new Canvas(Server.MapPath("rez/astro.jpg"));

[Visual Basic] Dim canvas As New Canvas(Server.MapPath("rez/astro.jpg"))

Default Export

So we have a comparison we'll start by exporting the GIF image without any color reduction. We export the GIF image from the Canvas into a GDI Bitmap. We then use the GDI bitmap to save the image to file.

Note that if we had exported the image from the Canvas in a different format, we would have had to save the bitmap using ImageFormat.Gif. This call automatically triggers GDI color reduction, which we are trying to avoid in this first output.

[C#] Bitmap bitmap = (Bitmap)Bitmap.FromStream(new MemoryStream(canvas.GetAs("dummy.gif")));

[Visual Basic] Dim bitmap As Bitmap = DirectCast(bitmap.FromStream(New MemoryStream(canvas.GetAs("dummy.gif"))), Bitmap)

GDI+ Color Reduction

We export the image using the color reduction available in GDI+. We copy the Canvas into our GDI+ Bitmap and then export it using ImageFormat.Gif.

[C#] bitmap = (Bitmap)Bitmap.FromStream(new MemoryStream(canvas.GetAs("dummy.bmp")));
bitmap.Save(Server.MapPath("Optimizing_GIFs_NET_7_gdireduced.gif"), ImageFormat.Gif);

[Visual Basic] bitmap = DirectCast(bitmap.FromStream(New MemoryStream(canvas.GetAs("dummy.bmp"))), Bitmap)
bitmap.Save(Server.MapPath("Optimizing_GIFs_NET_7_gdireduced.gif"), ImageFormat.Gif)

ImageGlue Color Reduction

Now we color reduce the canvas down to 25 colors using the ImageGlue adaptive palette. We then copy the Canvas into the GDI+ Bitmap and export it again.

[C#] XImage image = canvas.Image;
image.ReduceColors(new XPalette(XPalette.PaletteDefinition.Adaptive), 25, true);
canvas.DrawImage(image, new DrawOptions());
bitmap = (Bitmap)Bitmap.FromStream(new MemoryStream(canvas.GetAs("dummy.gif")));

[Visual Basic] Dim image As XImage = canvas.Image
image.ReduceColors(New XPalette(XPalette.PaletteDefinition.Adaptive), 25, True)
canvas.DrawImage(image, New DrawOptions())
bitmap = DirectCast(bitmap.FromStream(New MemoryStream(canvas.GetAs("dummy.gif"))), Bitmap)

Input and Output

Sample output images are shown below with respective file sizes. You can see that the color reduced image has been exported at a significantly reduced file size with little loss of quality.

Optimizing_GIFs_NET_7_original.gif [26650 bytes]

Optimizing_GIFs_NET_7_gdireduced.gif [20998 bytes]

Optimizing_GIFs_NET_7_igreduced.gif [17487 bytes]