【问题标题】:how to convert Base 64 string to GIF in go如何在 Go 中将 Base 64 字符串转换为 GIF
【发布时间】:2021-09-19 10:42:11
【问题描述】:

我在将 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
}

结果:

应该如何:

【问题讨论】:

    标签: go gif


    【解决方案1】:

    问题在于它是如何被解码的。 gif.Decode 返回 image.Image,但 gif.DecodeAll 返回 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)
        
    

    【讨论】:

      猜你喜欢
      • 2015-08-09
      • 2018-01-22
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 2013-09-26
      • 2013-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多