dongyong9224 2015-10-15 13:14
浏览 450
已采纳

如何将base64解码的png图像写入文件?

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条回答 默认 最新

  • dsg24156 2015-10-15 13:17
    关注

    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?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高通安卓11提取完整线刷包软件,或者优博讯dt50顺丰刷机包
  • ¥20 C,有个译码器,换了信道就跑不出原来数据
  • ¥15 MIMIC数据库安装问题
  • ¥60 基于JTag协议开发Fpga下载器上位机,哪位大🐂有偿指导?
  • ¥20 全书网Java爬取数据
  • ¥15 怎么获取红包封面的原始链接,并且获取红包封面序列号
  • ¥100 微信小程序跑脚本授权的问题
  • ¥100 房产抖音小程序苹果搜不到安卓可以付费悬赏
  • ¥15 STM32串口接收问题
  • ¥15 腾讯IOA系统怎么在文件夹里修改办公网络的连接