douyingzhan5905
2019-03-13 05:46 阅读 39
已采纳

从URL存储图像时如何写RIFF块头?

I just tried to download webp image from url, but I found something different when I try to process the stored image.

If I download the image from the browser, it can be decoded using x/image/webp package, but if I store the image using http.Get() then create a new file then io.Copy() the image, it says:

"missing RIFF chunk header"

I assume that I need to write some RIFF chunk header when I store it using golang code.

func main(){
    response, e := http.Get(URL)
    if e != nil {
        log.Fatal(e)
    }
    defer response.Body.Close()

    //open a file for writing
    file, err := os.Create('tv.webp')
    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!")

    imgData, err := os.Open("tv.webp")
    if err != nil {
        fmt.Println(err)
        return
    }
    log.Printf("%+v", imgData)
    image, err := webp.Decode(imgData)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(image.Bounds())
}

Here is the URL IMG URL

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dongxi5505 dongxi5505 2019-03-13 15:23

    download file is not webp type. it's png.

    package main
    
    import (
        "fmt"
        "image"
        "io"
        "log"
        "net/http"
        "os"
    
        _ "image/png"
    )
    
    func main() {
        response, e := http.Get("https://www.sony.com/is/image/gwtprod/0abe7672ff4c6cb4a0a4d4cc143fd05b?fmt=png-alpha")
        if e != nil {
            log.Fatal(e)
        }
        defer response.Body.Close()
    
        file, err := os.Create("dump")
        if err != nil {
            log.Fatal(err)
        }
        defer file.Close()
    
        _, err = io.Copy(file, response.Body)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println("Success!")
    
        imageFile, err := os.Open("dump")
        if err != nil {
            panic(err)
        }
    
        m, name, err := image.Decode(imageFile)
        if err != nil {
            panic(err)
        }
    
        fmt.Println("image type is ", name, m.Bounds())
    }
    
    点赞 评论 复制链接分享

相关推荐