如何在Go中创建透明的gif?

Dre*_*eur 4 gif go

当我在Go中编码gif时,背景全是黑色的.如何使背景透明?

这是我的http处理程序中的一些代码.(w是responseWriter)

m := image.NewRGBA(image.Rect(0, 0, pixelWidth, pixelHeight))
gif.Encode(w, m, &gif.Options{NumColors: 16}) 
Run Code Online (Sandbox Code Playgroud)

Dre*_*eur 7

我阅读了image/gif的源代码,发现调色板上必须有透明的颜色.

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{}) 
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这可以通过使用您自己的`*image.Paletted`作为要编码的图像(如图所示),或通过设置[`gif.Options`'s]来完成(https://golang.org/pkg/image/gif /#选项)`Quantizer`字段到[`draw.Quantizer`](https://golang.org/pkg/image/draw/#Quantizer),它将透明色放入调色板中(可能在检测到任何颜色时)图像中的透明度).`Quantizer`字段为nil时的默认值是使用没有透明度的静态调色板. (2认同)