英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论