gpt4 book ai didi

image - 格式无效 : not a PNG file

转载 作者:数据小太阳 更新时间:2023-10-29 03:36:41 25 4
gpt4 key购买 nike

我有一个代码可以从 AWS S3 下载图像、解码它们并调整它们的大小。该代码支持 PNG 和 JPG/JPEG 格式的图像。

以下是我从 AWS S3 下载图像的方法:

//downloads an image from S3
func downloadImage(bucket string, item string) error {
file, err := os.Create(strings.Split(item, "/")[len(strings.Split(item, "/"))-1])
if err != nil {
fmt.Println("Unable to open file", err)
return err
}
//create a new AWS session
sess, err := session.NewSession(&aws.Config{
Region: aws.String("eu-west-1")},
)
//create the s3 downloader
downloader := s3manager.NewDownloader(sess)

defer file.Close()
//download the image from S3
numBytes, err := downloader.Download(file,
&s3.GetObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(item),
})
if err != nil {
fmt.Println("Unable to download item", item)
fmt.Println(err)
return err
}

fmt.Println("Downloaded", file.Name(), numBytes, "bytes")
return nil
}

这是我解码图像的方式:

file, err := os.Open(image)
if err != nil {
fmt.Println(err)
return err
}
if strings.Split(image, ".")[len(strings.Split(image, "."))-1] == "jpg" ||
strings.Split(image, ".")[len(strings.Split(image, "."))-1] == "jpeg" {
img, err := jpeg.Decode(file)

if err != nil {
fmt.Println(err)
return err
}
file.Close()
}
else if strings.Split(image, ".")[len(strings.Split(image, "."))-1] == "png" {
img, err := png.Decode(file)

if err != nil {
fmt.Println(err)
return err
}
file.Close()
}

图像已成功下载、解码和调整大小。当代码下载一些 PNG 图像(不是全部)并尝试对其进行解码时,就会出现问题。不能。

它会产生以下错误:

png: invalid format: not a PNG file

我在 Ubuntu 16.04 上运行一切。奇怪的是,如果我使用图像查看器打开此图像,它会生成相同的错误。但是,如果我使用任何其他程序打开,例如:ImageMagick,图像打开时没有任何提示。

如何在 Golang 代码中解决这个问题?

最佳答案

显然,即使扩展名为.png,其内容类型为PNG,也不一定是PNG 图片。唯一确定的方法是检查图片标题。

用 GoLang 解决这个问题的一种方法是使用通用的 image.Decode() 函数,它根据 @icza 的建议检测图像类型

关于image - 格式无效 : not a PNG file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52148483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com