How to write a base64 decoded png image to file?

风流意气都作罢 提交于 2019-12-23 02:49:14

问题


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:


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?



来源:https://stackoverflow.com/questions/33149551/how-to-write-a-base64-decoded-png-image-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!