去图片上传

Go image upload

我目前正在执行以下操作将图像上传到我的服务器:

func (base *GuildController) GuildLogo(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
    ...
    logo, _, err := req.FormFile("logo")
    defer logo.Close()
    logoGif, format, err := image.Decode(logo)
    if err != nil {
        base.Error = "Error while decoding your guild logo"
        return
    }
    logoImage, err := os.Create(pigo.Config.String("template")+"/public/guilds/"+ps.ByName("name")+".gif")
    if err != nil {
        base.Error = "Error while trying to open guild logo image"
        return
    }
    defer logoImage.Close()
    //resizedLogo := resize.Resize(64, 64, logoGif, resize.Lanczos3)
    err = gif.Encode(logoImage, logoGif, &gif.Options{
        256,
        nil,
        nil,
    })
    if err != nil {
        base.Error = "Error while encoding your guild logo"
        return
    }
    ...
}

一切正常。但是gifs会丢失动画。

例如这是我要上传的 gif

这是保存的

不确定我做错了什么

正如评论中所暗示的,您只使用了一个框架:

func Decode(r io.Reader) (image.Image, error) Decode reads a GIF image from r and returns the first embedded image as an image.Image.

但是你需要

func DecodeAll(r io.Reader) (*GIF, error) DecodeAll reads a GIF image from r and returns the sequential frames and timing information.

func EncodeAll(w io.Writer, g *GIF) error EncodeAll writes the images in g to w in GIF format with the given loop count and delay between frames.

查看this post了解详情。

下面是一个将图像减慢到每帧 0.5 秒的示例:

package main

import (
    "image/gif"
    "os"
)

func main() {
    logo, err := os.Open("yay.gif")
    if err != nil {
        panic(err)
    }
    defer logo.Close()

    inGif, err := gif.DecodeAll(logo)
    if err != nil {
        panic(err)
    }

    outGif, err := os.Create("done.gif")
    if err != nil {
        panic(err)
    }
    defer outGif.Close()

    for i := range inGif.Delay {
        inGif.Delay[i] = 50
    }
    if err := gif.EncodeAll(outGif, inGif); err != nil {
        panic(err)
    }
}

结果:

旁注

即使在我的浏览器 (Firefox) 中看到动画输出图像,并且我可以在 GIMP 中看到帧,但我无法在桌面查看器(gifview、comix)上看到动画。我(还)不知道这是什么原因。