英文:
Convert Base64 string to PNG image and respond as http Response - Go language
问题
我正在尝试将一个base64编码转换为PNG图像,并将该图像作为Web请求的响应输出。我能在不在服务器上创建文件的情况下完成这个操作吗?
http的'ServeFile'只有在图像保存为文件时才起作用。但是,我想将base64字符串解码为图像数据,然后直接将其写入输出。
谢谢。
英文:
I am trying to convert a base64 encoding to a png image and ouput the image as response for a web request. Can I do this without creating a file in the server?
the 'ServeFile' of http works only when the image is saved as a file. but, I would like to decode the base64 string to image data and then directly write that to the output.
thanks.
答案1
得分: 5
使用base64.NewDecoder进行解码,例如:
func Handler(res http.ResponseWriter, req *http.Request) {
// 在这个例子中,客户端提交了base64图像,但是你可以使用任何io.Reader并将其传递给NewDecoder。
dec := base64.NewDecoder(base64.StdEncoding, req.Body)
res.Header().Set("Content-Type", "image/png")
io.Copy(res, dec)
}
英文:
Using base64.NewDecoder, for example :
func Handler(res http.ResponseWriter, req *http.Request) {
//in this example the client submits the base64 image, however
// you can use any io.Reader and pass it to NewDecoder.
dec := base64.NewDecoder(base64.StdEncoding, req.Body)
res.Header().Set("Content-Typee", "image/png")
io.Copy(res, dec)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论