go - 如何循环旋转图像以在 golang 中创建 GIF?

标签 go image-processing gif

我想使用 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/

相关文章:

objective-c - HDR 和全景图 : where to learn

c++ - 有没有办法在 OpenCV 中绘制图形?

ios - Swift - 从图像创建 GIF 并将其转换为 NSData

go - 格式错误的模块路径 "xxxx/xxxx/uuid"从基于 GOPATH 的 dep 迁移到 go mod 时第一个路径元素中缺少点

go - 如何将带时区的日期转换为 Javascript ISO 格式?

json - 将 JSON 结构附加到 JSON 文件 Golang

regex - Golang 正则表达式引用子匹配

c++ - C++中的图像处理

java - 从字节数组写入 GIF(在 Android 中)

java - 共享可绘制文件夹中的 gif 文件