将Base64字符串转换为PNG图像并作为http Response - Go语言进行响应

时间:2014-06-14 13:02:21

标签: go

我正在尝试将base64编码转换为png图像,并将图像作为Web请求的响应输出。我可以不在服务器中创建文件吗?

http的“ServeFile”仅在图像保存为文件时才起作用。但是,我想将base64字符串解码为图像数据,然后直接将其写入输出。

感谢。

1 个答案:

答案 0 :(得分:5)

使用base64.NewDecoder,例如:

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