Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a transparent gif in Go?

Tags:

go

gif

when I encode a gif in Go, the background is all black. How do I make the background transparent?

Here is some code in my http handler. (w is the responseWriter)

m := image.NewRGBA(image.Rect(0, 0, pixelWidth, pixelHeight))
gif.Encode(w, m, &gif.Options{NumColors: 16}) 
like image 353
Drew LeSueur Avatar asked May 14 '15 22:05

Drew LeSueur


People also ask

Can you make a GIF with transparency?

Unfortunately no, the GIF format doesn't support partial (alpha-channel) transparency, meaning any pixel can only be fully tansparent or fully opaque, so it's not possible to make partially transparent GIFs and achieve anti-aliasing effect against different backgrounds.


1 Answers

I read the source of image/gif and found that there just has to be a transparent color on your palette.

var palette color.Palette = color.Palette{
    image.Transparent,
    image.Black,
    image.White,
    color.RGBA{0, 255, 0, 255},
    color.RGBA{0, 100, 0, 255},
}

m := image.NewPaletted(image.Rect(0, 0, pixelWidth, pixelHeight), palette)
gif.Encode(w, m, &gif.Options{}) 
like image 52
Drew LeSueur Avatar answered Nov 15 '22 04:11

Drew LeSueur