Bitmap.MakeTransparent() and Bitmap.Save()

  • Thread starter Thread starter Dylan Nicholson
  • Start date Start date
D

Dylan Nicholson

Hi,

I've found quite a lot of messages and posts by developers at a loss
as to how to use MakeTransparent() to generate a GIF89 image with a
transparent color...but I've come across a particular problem that
I've yet to see mentioned, namely that using

bitmap.Save("filename.gif")

works just fine (correctly sets the transparent color in the GIF
file), whereas

bitmap.Save("filename.gif", ImageFormat.Gif);

doesn't work - the "transparent" color is consistently turned to
black.
Similarly for the Save(Stream, ImageFormat) overload, which is the one
I actually wanted to use (as I'd like to create the GIF file in
memory). Only workaround is to use the first form, saving to a temp
file, then load the file into memory.

I've also tried the other overloads for Bitmap.Save() with no luck.
Wondering if "ImageFormat.Gif" implies GIF87...but there is no
ImageFormat.Gif89.

Dylan
 
Wondering if "ImageFormat.Gif" implies GIF87...but there is no
ImageFormat.Gif89.

The easy way to tell is to open the file in a hex editor and examine the
signature.
bitmap.Save("filename.gif")

works just fine (correctly sets the transparent color in the GIF
file), whereas

bitmap.Save("filename.gif", ImageFormat.Gif);

doesn't work - the "transparent" color is consistently turned to
black.

That is interesting. I have not tried your method.

The Gdi+ encoder writes a local color table for the Gif
instead of a global color table!

Additionally, the Gif encoder creates a Gif "Extension Header".
According to the Gif 89a specification, a transparent index may
be indicate only with the corresponding transparency flag being
set! Otherwise it will be ignored.

In the "Extension Header" the transparent index is correctly written
to the transparent index field! However the transparency flag is not set!

Additionall, the Gif "Image Extension" header is optional per the spec.
So, when the image is read back into Gdi+ the Gif "Extension Header" is
ignored!
 
The easy way to tell is to open the file in a hex editor and examine the
signature.

Indeed...and once I did that I realised that the file that was saved
using the single-argument form of Bitmap.Save() wasn't a GIF at all,
but a PNG. Oops.
In the "Extension Header" the transparent index is correctly written
to the transparent index field! However the transparency flag is not set!
Hmm, well in the end I had to resort to the previously suggest trick
of saving as a GIF to a memory stream, reloading it, creating a new
Bitmap with just one of the palette entries having 0 alpha, copying
the bits, then resaving. Ridiculous, but seems to be only thing that
works.
 
Back
Top