I have a sample base64 data, that can be used in img
html tags like this:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEX/TQBcNTh/AAAACklEQVR4nGNiAAAABgADNjd8qAAAAABJRU5ErkJggg==
"/>
Demo
And I am fiddling around with a small golang program. In golang, how do I convert this static base64 encoded data into an image on the fly and then send it as an image in response.
Example:
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)
}
The code in the question is close. Try this:
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:]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With