Monday, July 18, 2022

[FIXED] How do I create a transparent gif in Go?

Issue

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

Solution

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


Answered By - Drew LeSueur
Answer Checked By - Gilberto Lyons (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.