开发者

convert png to gif with gdi+ (C#)

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开发者_StackOverflow中文版 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


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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜