英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论