Home > Backend Development > Golang > How Can a Go Beginner Efficiently Download and Save Images from a URL?

How Can a Go Beginner Efficiently Download and Save Images from a URL?

DDD
Release: 2024-12-08 19:00:13
Original
1046 people have browsed it

How Can a Go Beginner Efficiently Download and Save Images from a URL?

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!")
}
Copy after login

Explanation:

  • The HTTP response body is treated as a stream of bytes.
  • io.Copy is used to transfer the bytes from the stream to the local file.
  • Depending on the file size, the transfer can potentially take time, but it's an efficient approach for handling large images.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template