英文:
how to convert Base 64 string to GIF in go
问题
我遇到了将Base64字符串转换为GIF的问题。我尝试了以下方法:
unbased, err := base64.StdEncoding.DecodeString(bs64)
if err != nil {
panic("无法解码Base64")
}
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 Cloud Storage时,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
}
结果如下:
应该是这样的:
英文:
I'm having trouble converting a base 64 string to gif
i have tried the following.
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)
but when i uploaded it in the GCP/google cloud storage the GIF doesn't animate.
this is how i upload.
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
}
the result:
how it should be:
答案1
得分: 5
问题出在解码方式上。gif.Decode
返回一个 image.Image
,但 gif.DecodeAll
返回一个 gif.GIF
类型。
类似地,gif.EncodeAll
用于写入多个帧。
以下是适用于我的代码示例:
unbased, err := base64.StdEncoding.DecodeString(bs64)
if err != nil {
panic("无法解码 b64")
}
// 使用 DecodeAll 将数据加载到 gif.GIF 中
imgCoupon, err := gif.DecodeAll(bytes.NewReader(unbased))
imgCoupon.LoopCount = 0
// 使用 EncodeAll 将图像编码到缓冲区
var buff bytes.Buffer
gif.EncodeAll(&buff, imgCoupon)
英文:
The issue is with how it's being decoded. gif.Decode
returns an image.Image
, but gif.DecodeAll
returns a gif.GIF
type.
Similarly, gif.EncodeAll
is used to write multiple frames.
This is the code that works for me:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论