How do I create a transparent gif in Go?

huangapple go评论71阅读模式
英文:

How do I create a transparent gif in Go?

问题

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

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

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

你可以通过设置像素的Alpha通道来使背景透明。在创建RGBA图像时,将Alpha通道设置为透明(0),而不是不透明(255)。这样,只有非透明像素才会显示颜色。

以下是修改后的代码:

m := image.NewRGBA(image.Rect(0, 0, pixelWidth, pixelHeight))
for i := range m.Pix {
    if i%4 == 3 { // Alpha channel
        m.Pix[i] = 0 // Set alpha channel to transparent
    }
}
gif.Encode(w, m, &gif.Options{NumColors: 16})

这样,你的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}) 

答案1

得分: 8

我阅读了图像/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{})
英文:

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{}) 

huangapple
  • 本文由 发表于 2015年5月15日 06:27:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/30248493.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定