我在尝试用 Go 渲染 GIF 时遇到了问题。使用某种方法时,输出的 GIF 文件无法打开,但使用另一种方法则可以正常打开。我在 Go 中找到了 Rendering .gif,但它没有解决我的具体问题。
这是有问题的代码:
package main
import (
"bufio"
"fmt"
"image"
"image/color"
"image/gif"
"io"
"math"
"math/rand"
"os"
"time"
)
var palette = []color.Color{color.White, color.Black}
const (
whiteIndex = 0
blackIndex = 1
)
func main() {
w := bufio.NewWriter(os.Stdout)
lissajous(w)
}
func lissajous(out io.Writer) {
const (
cycles = 5
res = 0.001
size = 100
nframes = 64
delay = 8
)
rand.Seed(time.Now().UTC().UnixNano())
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)
}
err := gif.EncodeAll(out, &anim)
if err != nil {
return
} else {
fmt.Println(err)
}
}
以下是命令:
go build main.go
main > out.gif
然后,out.gif 无法被打开。不过,这个方法效果很好:
func main() {
fileName := "out.gif"
f, err3 := os.Create(fileName)
if err3 != nil {
fmt.Println("create file fail")
}
w := bufio.NewWriter(f)
lissajous(w)
w.Flush()
f.Close()
}
我很困惑为什么第一种方法无法创建功能性的 GIF 文件,而第二种方法却可以。这与 Go 处理文件写入或缓冲的方式有关吗?