格式无效:不是PNG文件

时间:2018-09-03 11:04:41

标签: image ubuntu go png

我有一个代码,可从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代码中克服这个问题?

1 个答案:

答案 0 :(得分:0)

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

使用GoLang克服此问题的一种方法是使用常规的image.Decode()函数,该函数根据@icza的建议根据注册表检测图像类型