Monday, December 7, 2009

How to generate a transparent GIF image using C#

There is apparently no easy way to generate a transparent GIF image using the .NET framework. Microsoft provided a method in the Bitmap class called MakeTransparent() but it doesn’t work for GIFs, it only seems to work for PNGs.

To create a transparent GIF you need to recreate the color table of the image using Imaging APIs. Unfortunately, this can be pretty slow for an ASP.NET Web application, and it has a lot of overhead, so I needed an alternative.

Solution:

The alternative is to alter the color table directly using the GIF specification. To implement this, I needed to save the non-transparent GIF to a MemoryStream, and then go through the binary data, updating the color table with the new transparency bits.