我想使用 Go 的各种图像处理工具在循环中重复旋转图像以创建 GIF,但我似乎无法弄清楚我做错了什么。此处,Gwenview 报告生成的 GIF 不是动画,并且仅包含一帧。
package main
import (
"image"
"image/color/palette"
"image/color"
"image/gif"
"image/draw"
"io"
"os"
"github.com/disintegration/imaging"
)
func main() {
rotate(os.Stdout)
}
func rotate(out io.Writer) {
f, _ := os.Open("myimage.png")
defer f.Close()
base, _, _ := image.Decode(f)
const (
rot = 45 // degrees
nframes = 5 // number of animation frames
delay = 20 // delay between frames in 10ms units
)
bounds := base.Bounds()
anim := gif.GIF{LoopCount: nframes}
for i := 0; i < nframes; i++ {
img := imaging.Rotate(base, float64(360 - (rot * i)), color.Transparent)
bounds = img.Bounds()
palettedImg := image.NewPaletted(bounds, palette.Plan9)
draw.Draw(palettedImg, bounds, img, bounds.Min, draw.Src)
anim.Delay = append(anim.Delay, delay)
anim.Image = append(anim.Image, palettedImg)
}
gif.EncodeAll(out, &anim) // NOTE: ignoring encoding errors
}
最佳答案
问题确实是您忽略了错误消息。永远不要那样做,始终准确地处理错误!在您的特定情况下,您的示例不起作用,因为您将新创建的图像边界设置为原始图像,但是因为在每个帧迭代中您都在旋转图像,所以它们的尺寸超出了原始边界。如果您没有忽略编码错误,则可以捕获问题所在。
err := gif.EncodeAll(out, &anim)
if err != nil {
fmt.Printf("%v", err)
}
错误:
$ gif: image block is out of bounds
关于go - 如何循环旋转图像以在 golang 中创建 GIF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72504751/