Go语言 image.decode在解码.png文件时返回错误

bsxbgnwa  于 2023-04-18  发布在  Go
关注(0)|答案(2)|浏览(327)

看起来image.Decode(第24行)在解码图像时返回了一个错误。图像“test2.png”存在于文件的目录中,并且是一个函数PNG图像。作为参考,此代码应该创建一个相同分辨率的新图像,并从test2.png中随机选择一种颜色。任何帮助都将不胜感激。
代码:

package main

import (
    "fmt"
    "image"
    "image/color"
    _ "image/jpeg"
    "image/png"
    "math/rand"
    "os"
)

func main() {
    file, err := os.Open("test2.png")
    if err != nil {
        fmt.Println("0 ", err)
        return
    }
    imageInConfig, _, err := image.DecodeConfig(file)
    if err != nil {
        fmt.Println("1 ", err)
        return
    }
    imageIn, fileType, err := image.Decode(file)
    fmt.Println("File type: ", fileType)
    if err != nil {
        fmt.Println("2 ", err)
        return
    }

    outputWidth := imageInConfig.Width
    outputHeight := imageInConfig.Height
    imageOut := image.NewRGBA(image.Rectangle{image.Point{0, 0}, image.Point{outputWidth, outputHeight}})

    r, g, b, a := imageIn.At(int(rand.Intn(imageInConfig.Width)), int(rand.Intn(imageInConfig.Height))).RGBA()
    pixelColor := color.RGBA{uint8(r), uint8(g), uint8(b), uint8(a)}

    for x := 0; x < outputWidth; x++ {
        for y := 0; y < outputHeight; y++ {
            imageOut.Set(x, y, pixelColor)
        }
    }

    fileCreated, _ := os.Create("test2out.png")
    png.Encode(fileCreated, imageOut)
}

输出的错误为:

image: unknown format
kjthegm6

kjthegm61#

您试图从同一个io.reader(文件)读取两次。

image.DecodeConfig(file)

第二次在

image.Decode(file)

第二次尝试从同一个io.reader读取时,将得到EOF
当Read在成功阅读n〉0字节后遇到错误或文件结束条件时,它返回读取的字节数。它可以返回(non-nil)来自同一调用的错误或返回错误这种一般情况的一个示例是,在输入流的末尾返回非零字节数的Reader可以返回err == 0(并且n == 0)。EOF或err == nil。下一次读取应返回0,EOF。
在这里阅读更多关于它https://golang.org/pkg/io/#Reader
一些快速和简单的你可以做的是打开文件两次

file, err := os.Open("test2.png")
if err != nil {
    fmt.Println("0 ", err)
    return
}
imageInConfig, _, err := image.DecodeConfig(file)
if err != nil {
    fmt.Println("1 ", err)
    return
}

file2, err := os.Open("test2.png")
if err != nil {
    fmt.Println("3 ", err)
    return
}
imageIn, _, err := image.Decode(file2)
if err != nil {
    fmt.Println("4 ", err)
    return
}

或者,您可以尝试多次阅读同一个文件。How to read multiple times from same io.Reader

ssgvzors

ssgvzors2#

您需要在以下行image.DecodeConfig(file)image.Decode(file)之间进行此调用:

file.Seek(0, io.SeekStart)

相关问题