convert png to gif with gdi+ (C#)

烂漫一生 提交于 2019-12-11 00:07:33

问题


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:


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




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/1989450/convert-png-to-gif-with-gdi-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!