Convert png to gif using gdi + (C #)

I have a png file that I need to convert to a gif file. It has a transparent part in it, and when I save it, the transparent part turns black instead of transparent. here is my code:

FileStream imgStream = new FileStream(outputFile, FileMode.Create, FileAccess.Write); Image.FromFile(imageInput).Save(imgStream, ImageFormat.Gif); 

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

You see what is wrong here?

michelle

+2
source share
3 answers

PNG uses alpha transparency, which means that each pixel, in addition to its color, also contains a value indicating its transparency (called alpha ). This allows translucent PNG images.

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

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

You need to skip the pixels in the image, replacing any color that has alpha 0 with Color.Transparent .

EDIT : you need to call MakeTransparent

+5
source

As noted by other posters, GIF does not support alpha transparency, but one color in GIF can be set as completely transparent. You can convert PNG to a 256-color bitmap palette and replace any fully transparent (A = 255) with Colors.Transparent , and then save the new image as a GIF.

See ImageAttributes and ImageAttributes details.

+3
source

GIF image format does not support alpha transparency.

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

A is used to indicate transparency, and I would suggest that the converter ignores the value of A.

PNG

GIF

+2
source

All Articles