tags:

views:

497

answers:

3

Hi,

i have a png file which must be converted to a gif file. There is a transparent part in it, and when i save it the transparent part is black in stead of transparent. here's my code:

FileStream imgStream = new FileStream(outputFile, FileMode.Create, FileAccess.Write);

Image.FromFile(imageInput).Save(imgStream, ImageFormat.Gif);

here, imageinput is the fullpath to my png, and output file is the filefullpath with .gif extension.

can you see what is wrong here?

michel

+1  A: 

The GIF image format does not support alpha transparency.

  • GIF supports 24-bit RGB.
  • PNG supports 32-bit RGBA.

The A is used to specify transparency and I would imagine the converter ignores the A value.

PNG

GIF

ChaosPandion
what do you mean by that? is transparent in png something else than transparent in gif?
Michel
+4  A: 

PNG uses alpha transparency, meaning that each pixel, in addition to its color, also contains a value denoting how transparent it is (called alpha). This allows PNG images to be semi-transparent.

GIF images use binary transparency, meaning that each pixel only contains a color, but one of the possible colors is Transparent.

Therefore, the transparent parts of the PNG will be colored black, but completely transparent.
When you save the GIF file, the alpha value is ignored, resulting in black.

You need to loop through the pixels in the image, replacing any color which has an alpha of 0 with Color.Transparent.

EDIT: You need to call MakeTransparent

SLaks
Hi, thanks for your answer. Now the transparent color is shown as white... when i do Color.Orange all transparent pixels are shown orange, but when i do Color.Transparent all transparent pixels are shown white. Can it be a problem that a lot of the pixels are white? Or should i 'say' which color should be used to be the transparent one?
Michel
looking in intellisense learned that color.transparent is actually white? is there a way to make the transparent color for example green and say to the gif 'green must be transparent'?
Michel
Ah! the makeTransparent did the trick. Thanks.
Michel
+3  A: 

As other posters have pointed out, GIF doesn't support alpha transparency--but a single color in the GIF can be set as fully-transparent. You could convert the PNG to a 256-color paletted bitmap and replace any fully-transparent (A = 255) to Colors.Transparent, and then save the new image as a GIF.

See ImageAttributes and ColorMap for more information.

Ben M