JPOZ.COM/ Archive
← WritingArchive

Making gifs with Go

Go's standard library has a gif decoder, but sadly no encoder. I found an encode on github here. Unfortunalty it written in the main package so i forked it and pulled it into its own package: github.com/jpoz/gifencoder. Now we can easily decode a gif, play around with it and encode it back to a file.

For this example I'm going to do something pretty basic: Take a gif and mirror the animation. Below is my target gif:

nom.gif

Here's the code:

package main

import (
	"github.com/jpoz/gifencoder"
	"image/gif"
	"os"
)

func main() {
	file, _ := os.Open("nom.gif")
	g, _ := gif.DecodeAll(file)

	for _, img := range g.Image { // iterate over frames
		for x := 0; x < img.Bounds().Max.X/2; x++ { // half of the x space
			for y := 0; y < img.Bounds().Max.Y; y++ { // all of the y space
				// find the mirror pixel's color
				c := img.At(img.Bounds().Max.X-x, img.Bounds().Max.Y-y)
				// set it
				img.Set(x, y, c)
			}
		}
	}

	file, _ = os.Create("new_nom.gif")
	_ = gifencoder.EncodeAll(file, g)
}

Here's what we get:

new_nom.gif