Load image from url in golang

huangapple go评论95阅读模式
英文:

Load image from url in golang

问题

我在golang中将图像加载到image.Image格式中,但是出现了以下错误:

"image: unknown format"

这是我的函数:

import "image"

url := "https://i.imgur.com/m1UIjW1.jpg"
func loadImageFromURL(URL string) (image.Image, error) {
    //从URL获取响应字节
    response, err := http.Get(URL)
    if err != nil {
        return nil, err
    }
    defer response.Body.Close()

    if response.StatusCode != 200 {
        return nil, errors.New("received non 200 response code")
    }

    img, _, err := image.Decode(response.Body)
    if err != nil {
        return nil, err
    }

    return img, nil
}

缺少的是这个导入:

import _ "image/jpeg"
英文:

I load an image in golang to the image.Image format but i get this error:

"image: unknown format"

This is my function:

import "image"

url := "https://i.imgur.com/m1UIjW1.jpg"
func loadImageFromURL(URL string) (image.Image, error) {
	//Get the response bytes from the url
	response, err := http.Get(URL)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()

	if response.StatusCode != 200 {
		return nil, errors.New("received non 200 response code")
	}

	img, _, err := image.Decode(response.Body)
	if err != nil {
		return nil, err
	}

	return img, nil
}

What is was missing was this import:

import _ "image/jpeg"

答案1

得分: 0

很抱歉,你的代码(在你的问题的原始版本中)是不完整的,具体来说,缺少了URL和重要的导入语句。了解URL很重要,因为也许它根本不返回图像。导入语句很重要,因为根据image的文档所述:

> 解码任何特定的图像格式需要事先注册解码器函数。注册通常是自动完成的,作为初始化该格式包的副作用,因此,要解码PNG图像,只需要在程序的主包中写入

> import _ "image/png"

> _ 的意思是仅为了导入一个包以获取其初始化副作用。

URL错误和导入缺失这两个错误都可以解释你看到的错误。

如果两者都正确执行,代码在我这里可以正常工作,无需更改。

英文:

Unfortunately your code (in the original version of your question) is incomplete, specifically it is missing the URL and your import statements as crucial information. The URL is important to know because maybe it does not return an image at all. The import statement is important because to cite from the documentation of image:

> Decoding any particular image format requires the prior registration
> of a decoder function. Registration is typically automatic as a side
> effect of initializing that format's package so that, to decode a PNG
> image, it suffices to have
>
> import _ "image/png"
> in a program's main package. The _ means to
> import a package purely for its initialization side effects.

Both errors (wrong URL, missing import) would explain the error you see.

If both are done correctly the code works fine for me without changes.

huangapple
  • 本文由 发表于 2022年7月16日 19:58:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/73004000.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定