Home >Backend Development >Golang >How to Efficiently Save an Image from a URL to a File in Go?
Saving Image from URL to File in Go
In Go, downloading and saving images from URLs can be achieved through the net/http package. The provided code has a minor issue in converting the image data from type image.Image to []byte before writing it to a file. However, there's a more straightforward method to handle this task:
Modified Approach:
In the modified approach, we avoid image decoding and directly copy the response body into a file. This is made possible by the convenience of io.Copy, which allows seamless transfer of data streams. Here's the revised code:
import ( "fmt" "io" "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("/tmp/image.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 downloaded and saved successfully!") }
Key Points:
The above is the detailed content of How to Efficiently Save an Image from a URL to a File in Go?. For more information, please follow other related articles on the PHP Chinese website!