Saving Images from URLs
Question:
As a novice in Go, how can I retrieve an image from a URL and save it locally?
Initial Approach:
The provided code attempts to decode the image using image.Decode, which is designed for decoding image files. However, the retrieved data should be treated as raw bytes instead.
Updated Approach:
To save the image directly from the URL, we can employ ioutil.ReadFrom to copy the response body, which contains the image data, to a local file.
Here's the modified code:
package main import ( "fmt" "io" "io/ioutil" "log" "net/http" "os" ) func main() { url := "http://i.imgur.com/m1UIjW1.jpg" response, err := http.Get(url) if err != nil { log.Fatal(err) } defer response.Body.Close() file, err := os.Create("/images/asdf.jpg") if err != nil { log.Fatal(err) } defer file.Close() _, err = io.Copy(file, response.Body) if err != nil { log.Fatal(err) } fmt.Println("Image saved successfully!") }
Explanation:
The above is the detailed content of How Can a Go Beginner Efficiently Download and Save Images from a URL?. For more information, please follow other related articles on the PHP Chinese website!