Save an image from url to file

后端 未结 3 1519
猫巷女王i
猫巷女王i 2020-12-28 15:07

Very new to Go (first simple project I\'m working on).

Question: How do I get an image from URL and then save it to my computer?

Here\'s what I have so far:<

相关标签:
3条回答
  • 2020-12-28 15:37

    There is no need to decode the file. Simply copy the response body to a file you've opened. Here's the deal in the modified example:

    1. response.Body is a stream of data, and implements the Reader interface - meaning you can sequentially call Read on it, as if it was an open file.
    2. The file I'm opening here implements the Writer interface. This is the opposite - it's a stream you can call Write on.
    3. io.Copy "patches" a reader and a writer, consumes the reader stream and writes its contents to a Writer.

    This is one of my favorite things about go - implicit interfaces. You don't have to declare you're implementing an interface, you just have to implement it to be used in some context. This allows mixing and matching of code that doesn't need to know about other code it's interacting with.

    package main

    import (
        "fmt"
        "io"
        "log"
        "net/http"
        "os"
    )
    
    func main() {
        url := "http://i.imgur.com/m1UIjW1.jpg"
        // don't worry about errors
        response, e := http.Get(url)
        if e != nil {
            log.Fatal(e)
        }
        defer response.Body.Close()
    
        //open a file for writing
        file, err := os.Create("/tmp/asdf.jpg")
        if err != nil {
            log.Fatal(err)
        }
        defer file.Close()
    
        // Use io.Copy to just dump the response body to the file. This supports huge files
        _, err = io.Copy(file, response.Body)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println("Success!")
    }
    
    0 讨论(0)
  • 2020-12-28 15:39
    package main
    
    import (
        "io"
        "net/http"
        "os"
        "fmt"
    )
    
    func main() {
        img, _ := os.Create("image.jpg")
        defer img.Close()
    
        resp, _ := http.Get("http://i.imgur.com/Dz2r9lk.jpg")
        defer resp.Body.Close()
    
        b, _ := io.Copy(img, resp.Body)
        fmt.Println("File size: ", b)
    }
    
    0 讨论(0)
  • 2020-12-28 15:52

    What is the type of response.Body? You should just convert that into a []byte if it is not and write that to disk. There is no reason to use the image class unless you have some reason to treat the data as an image. Just treat the data as a series of bytes and write it to the disk.

    0 讨论(0)
提交回复
热议问题