Load image from url in golang

Viewed 136

I load an image in golang to the image.Image format but i get this error:

"image: unknown format"

This is my function:

import "image"

url := "https://i.imgur.com/m1UIjW1.jpg"
func loadImageFromURL(URL string) (image.Image, error) {
    //Get the response bytes from the url
    response, err := http.Get(URL)
    if err != nil {
        return nil, err
    }
    defer response.Body.Close()

    if response.StatusCode != 200 {
        return nil, errors.New("received non 200 response code")
    }

    img, _, err := image.Decode(response.Body)
    if err != nil {
        return nil, err
    }

    return img, nil
}

What is was missing was this import:

import _ "image/jpeg"
1 Answers

Unfortunately your code (in the original version of your question) is incomplete, specifically it is missing the URL and your import statements as crucial information. The URL is important to know because maybe it does not return an image at all. The import statement is important because to cite from the documentation of image:

Decoding any particular image format requires the prior registration of a decoder function. Registration is typically automatic as a side effect of initializing that format's package so that, to decode a PNG image, it suffices to have

import _ "image/png" 

in a program's main package. The _ means to import a package purely for its initialization side effects.

Both errors (wrong URL, missing import) would explain the error you see.

If both are done correctly the code works fine for me without changes.

Related