Today, I read the "Go Language Bible" of golang Chinese community translation, and in Chapter 1.4, I talked about animating gif with go, which is very interesting to share with everyone.
Package Main
Import (
"Image"
"Image/color"
"Image/gif"
"IO"
"Math"
"Math/rand"
"OS"
)
var palette = []color. Color{color. White, color. Black}//Palette
Const (
Whiteindex = 0
Blackindex = 1
)
Func Main () {
Lissajous (OS. Stdout)
}
Func lissajous (out IO. Writer) {
Const (
Cycles = 5
Res = 0.001
Size = 100
Nframes = 64
Delay = 8
)
Freq: = Rand. Float64 () * 3.0
ANIM: = gif. Gif{loopcount:nframes}
Phase: = 0.0
For I: = 0; i < nframes; i++ {
Rect: = image. Rect (0, 0, 2*size+1, 2*size+1)
IMG: = image. newpaletted (rect, palette)
For t: = 0.0; T < Cycles*2*math. Pi; T + = res {
x: = Math. Sin (t)
Y: = Math. Sin (t*freq + phase)
Img. Setcolorindex (Size+int (x*size+0.5), Size+int (y*size+0.5), Blackindex)
}
Phase + = 0.1
Anim. Delay = Append (anim. Delay, delay)
Anim. Image = Append (anim. Image, IMG)
}
Gif. Encodeall (out, &anim)
}
$./gif >out.gif
Go making gif animations