Best way to read image from URL into image.Decode()

5,041 views
Skip to first unread message

Douglas Fils

unread,
Apr 12, 2012, 9:43:26 AM4/12/12
to golan...@googlegroups.com
I'm new to Go so this has me a bit confused.

I can read an image off the net with:

res, err = http.Get("URL HERE")
f, err := ioutil.ReadAll(res.Body)

but I need that in 

m, _, err := image.Decode(f)

but f is a []byte not the expect type io.Reader

There is obviously a way to read the []byte as io.Reader but I'm really confused trying to find it.


Message has been deleted
Message has been deleted

Douglas Fils

unread,
Apr 12, 2012, 10:08:52 AM4/12/12
to golan...@googlegroups.com
Peter,
  Thanks!   works perfectly..     I'll check out newReader too.   Appreciate the help!

Take care
Doug


On Thursday, April 12, 2012 8:54:56 AM UTC-5, Peter Thrun wrote:
The response body is an io.Reader.  Use the body directly instead of slurping it up into a byte slice.  

res, err = http.Get("URL HERE")
if err != nil || res.StatusCode != 200 {
    // handle errors
}
defer res.Body.Close()
m, _, err := image.Decode(res.Body)
if err != nil {
   // handle error
}

ajk...@gmail.com

unread,
Nov 13, 2018, 3:52:16 PM11/13/18
to golang-nuts
Awesome! I was just looking for the same answer!

Thanks a lot guys.
Reply all
Reply to author
Forward
0 new messages