The picture/gif package deal of Go’s customary library makes it fairly straightforward to create animated GIF pictures. All you must do is create your particular person frames as an array of *picture.Paletted and use gif.EncodeAll() to encode them into an animated GIF.
When you get to the purpose the place you must do one thing extra superior than importing present pictures or drawing primary shapes, you would possibly end up utilizing further packages just like the superior gg which I extremely suggest.
Right here issues begin to get fascinating as a result of gif.EncodeAll() expects paletted pictures as its enter, whereas gg will create RGBA pictures by default.
The apparent method to clear up this downside can be to create your frames with gg, export them as PNG pictures and use gif.Decode() to learn your newly created PNG information and decode them to paletted GIF pictures which you could re-encode into an animated GIF.
Whereas this works simply high quality, it isn’t actually a superb resolution since there’s loads of encoding and decoding overhead and it will result in the creation of a number of PNG pictures on disk that we’re not actually interested by.
What we’re going to do as an alternative is that this: we’re going create our frames with gg as earlier than, create a brand new pletted picture in reminiscence, and draw the RGBA picture we created with gg onto the brand new picture utilizing picture/draw successfully changing it from RGBA to paletted:
dc.DrawCircle(x, y, 20) dc.SetRGBA(0, 0, 0, 1) dc.Fill() img := dc.Picture() bounds := img.Bounds() dst := picture.NewPaletted(bounds, palette.WebSafe) draw.Draw(dst, bounds, img, bounds.Min, draw.Src)
Now we will append our new paletted picture to our array of particular person frames and encode them into an animated GIF: