如何在 go 中将 Base 64 字符串转换为 GIF

how to convert Base 64 string to GIF in go

我在将 base 64 字符串转换为 gif 时遇到问题 我尝试了以下方法。

unbased, err := base64.StdEncoding.DecodeString(bs64)
    if err != nil {
        panic("Cannot decode b64")
    }
    var imgCoupon image.Image
    imgCoupon, err = gif.Decode(bytes.NewReader(unbased))

    var opt gif.Options
    opt.NumColors = 256
    var buff bytes.Buffer
    gif.Encode(&buff, imgCoupon, &opt)

但是当我将它上传到 GCP/google 云存储时,GIF 没有动画。

这是我上传的方式。

sw := storageClient.Bucket(bucket).Object("test"+"_file"+".gif").NewWriter(ctx)

if _, err := io.Copy(sw, &buff); err != nil {
    c.JSON(http.StatusInternalServerError, gin.H{
        "message": err.Error(),
        "error":   true,
    })
    return
}

结果:

应该如何:

问题在于它的解码方式。 gif.Decode returns image.Image,但 gif.DecodeAll returns gif.GIF 类型。

同理,gif.EncodeAll用于写入多帧

这是适合我的代码:

unbased, err := base64.StdEncoding.DecodeString(bs64)
if err != nil {
    panic("Cannot decode b64")
}

// Use DecodeAll to load the data into a gif.GIF
imgCoupon, err := gif.DecodeAll(bytes.NewReader(unbased))
imgCoupon.LoopCount = 0

// EncodeAll to the buffer
var buff bytes.Buffer
gif.EncodeAll(&buff, imgCoupon)