Sunday, July 17, 2022

[FIXED] How can I rotate an image in a loop in order to create a GIF in golang?

Issue

I want to repeatedly rotate an image in a loop, in order to create a GIF, using Go's various image processing tools, but I can't seem to figure out what I'm doing wrong. Here, Gwenview reports that the GIF produced is not animated, and contains only one frame.


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
}

Solution

The problem is indeed that you are ignoring the error messages. Never do that, always handle the errors accurately! In your specific case your example is not working because you are setting the newly created image bounds to the original image, but because on each frame iteration you are rotating the image, their dimensions are going outside of the original bounds. If you didn't ignored the encoding errors, you could captured what's going wrong.

err := gif.EncodeAll(out, &anim)
if err != nil {
    fmt.Printf("%v", err)
}

The error:

$ gif: image block is out of bounds  


Answered By - Endre Simo
Answer Checked By - Katrina (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.