如何在Go中将Base64字符串转换为GIF
我在将 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返回一个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)