如何在Go中将Base64字符串转换为GIF格式的图片。

huangapple go评论79阅读模式
英文:

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
}

结果如下:

如何在Go中将Base64字符串转换为GIF格式的图片。

应该是这样的:

如何在Go中将Base64字符串转换为GIF格式的图片。

英文:

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:

如何在Go中将Base64字符串转换为GIF格式的图片。

how it should be:

如何在Go中将Base64字符串转换为GIF格式的图片。

答案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)
    

huangapple
  • 本文由 发表于 2021年7月9日 10:23:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/68310534.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定