如何写一个base64解码的PNG图像文件? [英] How to write a base64 decoded png image to file?

查看:192
本文介绍了如何写一个base64解码的PNG图像文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用以下代码编写一个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))

界限没问题。最后一行的错误信息是:

lockquote

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


很明显,因为image.Image不是byte []。但是,我该如何转换它?或者是否有更简单的版本来做到这一点。

使用 png.Encode() 来编码 image.Image 添加到文件( b $ b

最后一行应该替换为:

  err = png.Encode(imgFile,pngImage)

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



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



在Golang绘制一个矩形?


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.

解决方案

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):

Draw a rectangle in Golang?

这篇关于如何写一个base64解码的PNG图像文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆