将Base64字符串转换为PNG图像,并作为HTTP响应返回 – Go语言

huangapple go评论75阅读模式
英文:

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

huangapple
  • 本文由 发表于 2014年6月14日 21:02:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/24220202.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定