我有一个64位数据样本,可以在像这样的img标签中使用 -
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEX/TQBcNTh/AAAACklEQVR4nGNiAAAABgADNjd8qAAAAABJRU5ErkJggg==
"/>
我正在摆弄一个小的golang程序。 在golang中,如何将这个静态基础64编码数据动态转换为图像,然后将其作为响应发送给图像。
前 -
http.HandleFunc("/getImage", imageHandler)
func image(res http.ResponseWriter, req *http.Request) {
data := "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEX/TQBcNTh/AAAACklEQVR4nGNiAAAABgADNjd8qAAAAABJRU5ErkJggg=="
// Data is the base64 encoded image
dec := b64.NewDecoder(b64.StdEncoding, data)
res.Header().Set("Content-Type", "image/png")
io.Copy(res, dec)
}
答案 0 :(得分:6)
问题中的代码很接近。试试这个:
data := "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEX/TQBcNTh/AAAACklEQVR4nGNiAAAABgADNjd8qAAAAABJRU5ErkJggg=="
// The actual image starts after the ","
i := strings.Index(data, ",")
if i < 0 {
log.Fatal("no comma")
}
// pass reader to NewDecoder
dec := base64.NewDecoder(base64.StdEncoding, strings.NewReader(data[i+1:]))