我想在回圈中反復旋轉影像,以創建 GIF,使用 Go 的各種影像處理工具,但我似乎無法弄清楚我做錯了什么。在這里,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
}
uj5u.com熱心網友回復:
問題確實是您忽略了錯誤訊息。永遠不要那樣做,總是準確地處理錯誤!在您的特定情況下,您的示例不起作用,因為您將新創建的影像邊界設定為原始影像,但是因為在每次幀迭代中您都在旋轉影像,它們的尺寸超出了原始邊界。如果您沒有忽略編碼錯誤,您可以捕捉到問題所在。
err := gif.EncodeAll(out, &anim)
if err != nil {
fmt.Printf("%v", err)
}
錯誤:
$ gif: image block is out of bounds
uj5u.com熱心網友回復:
這是我用來制作gif. 也許它可以幫助您找到解決方案。
package main
import (
"fmt"
"image"
"image/color"
"image/gif"
"math"
"os"
)
type Circle struct {
X, Y, R float64
}
func (c *Circle) Brightness(x, y float64) uint8 {
var dx, dy float64 = c.X - x, c.Y - y
d := math.Sqrt(dx*dx dy*dy) / c.R
if d > 1 {
return 0
} else {
return 255
}
}
func main() {
var w, h int = 240, 240
var palette = []color.Color{
color.RGBA{0x00, 0x00, 0x00, 0xff}, color.RGBA{0x00, 0x00, 0xff, 0xff},
color.RGBA{0x00, 0xff, 0x00, 0xff}, color.RGBA{0x00, 0xff, 0xff, 0xff},
color.RGBA{0xff, 0x00, 0x00, 0xff}, color.RGBA{0xff, 0x00, 0xff, 0xff},
color.RGBA{0xff, 0xff, 0x00, 0xff}, color.RGBA{0xff, 0xff, 0xff, 0xff},
}
var images []*image.Paletted
var delays []int
var hw, hh float64 = float64(w / 2), float64(h / 2)
circles := []*Circle{&Circle{}, &Circle{}, &Circle{}}
steps := 20
// Set up for the animtion loop
for step := 0; step < steps; step {
img := image.NewPaletted(image.Rect(0, 0, w, h), palette)
images = append(images, img)
delays = append(delays, 0)
θ := 2.0 * math.Pi / float64(steps) * float64(step)
for i, circle := range circles {
θ0 := 2 * math.Pi / 3 * float64(i)
circle.X = hw - 40*math.Sin(θ0) - 20*math.Sin(θ0 θ)
circle.Y = hh - 40*math.Cos(θ0) - 20*math.Cos(θ0 θ)
circle.R = 50
}
for x := 0; x < w; x {
for y := 0; y < h; y {
img.Set(x, y, color.RGBA{
circles[0].Brightness(float64(x), float64(y)),
circles[1].Brightness(float64(x), float64(y)),
circles[2].Brightness(float64(x), float64(y)),
255,
})
}
}
}
f, err := os.OpenFile("rgb.gif", os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
gif.EncodeAll(f, &gif.GIF{
Image: images,
Delay: delays,
})
}
TLDR;有關完整示例,請參見要點
向nitoyon 致敬
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/486282.html
