How to write a base64 decoded png image to file?

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

How to write a base64 decoded png image to file?

问题

我尝试使用以下代码将一个base64的png图像写入文件:

imageReader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(Images[i]))
pngImage, _, err := image.Decode(imageReader)
if err != nil {
  beego.Error(err)
}
bounds := pngImage.Bounds()
if imgFile, err = os.Create(fileName + ".png"); err != nil {
   return Data{}
}
defer imgFile.Close()
_, err = imgFile.Write([]byte(pngImage))

bounds是正确的。最后一行的错误信息是:

无法将pngImage(类型为image.Image)转换为[]byte类型

显然,因为image.Image不是byte[]类型。但是我该如何进行转换呢?或者是否有更简单的方法来实现这个?

英文:

I try to write a base64 png image to file with following code:

imageReader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(Images[i]))
pngImage, _, err := image.Decode(imageReader)
if err != nil {
  beego.Error(err)
}
bounds := pngImage.Bounds()
if imgFile, err = os.Create(fileName + ".png"); err != nil {
   return Data{}
}
defer imgFile.Close()
_, err = imgFile.Write([]byte(pngImage))

The bounds are ok. The error message for the last line is

> cannot convert pngImage (type image.Image) to type []byte

Obviously, because an image.Image is not a byte[]. But how can I convert it? Or is there even a simpler version to do this.

答案1

得分: 4

使用png.Encode()image.Image编码为文件(io.Writer)。

最后一行应替换为:

err = png.Encode(imgFile, pngImage)

png.Encode()将生成并将字节序列发送到指定的io.Writer(当然可以是os.File),以PNG格式描述指定的图像。

还可以查看这个答案,其中包含一个完整的示例,将图像写入文件(以PNG格式):

https://stackoverflow.com/questions/28992396/draw-a-rectangle-in-golang

英文:

Use png.Encode() to encode an image.Image to a file (io.Writer).

The last line should be replaced with:

err = png.Encode(imgFile, pngImage)

png.Encode() will produce and send the byte sequence to the specified io.Writer (which can be an os.File of course), describing the specified image in PNG format.

Also check out this answer which contains a complete example writing an image to a file (in PNG format):

https://stackoverflow.com/questions/28992396/draw-a-rectangle-in-golang

huangapple
  • 本文由 发表于 2015年10月15日 21:14:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/33149551.html
匿名

发表评论

匿名网友

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

确定