Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang convert base64 data into image on the fly and send response

Tags:

base64

go

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)
}
like image 871
Ajey Avatar asked Oct 15 '17 17:10

Ajey


1 Answers

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:]))
like image 176
Bayta Darell Avatar answered Oct 31 '22 22:10

Bayta Darell