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

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

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

  1. package main
  2. import (
  3. "fmt"
  4. "image"
  5. "image/color"
  6. _ "image/jpeg"
  7. "image/png"
  8. "math/rand"
  9. "os"
  10. )
  11. func main() {
  12. file, err := os.Open("test2.png")
  13. if err != nil {
  14. fmt.Println("0 ", err)
  15. return
  16. }
  17. imageInConfig, _, err := image.DecodeConfig(file)
  18. if err != nil {
  19. fmt.Println("1 ", err)
  20. return
  21. }
  22. imageIn, fileType, err := image.Decode(file)
  23. fmt.Println("File type: ", fileType)
  24. if err != nil {
  25. fmt.Println("2 ", err)
  26. return
  27. }
  28. outputWidth := imageInConfig.Width
  29. outputHeight := imageInConfig.Height
  30. imageOut := image.NewRGBA(image.Rectangle{image.Point{0, 0}, image.Point{outputWidth, outputHeight}})
  31. r, g, b, a := imageIn.At(int(rand.Intn(imageInConfig.Width)), int(rand.Intn(imageInConfig.Height))).RGBA()
  32. pixelColor := color.RGBA{uint8(r), uint8(g), uint8(b), uint8(a)}
  33. for x := 0; x < outputWidth; x++ {
  34. for y := 0; y < outputHeight; y++ {
  35. imageOut.Set(x, y, pixelColor)
  36. }
  37. }
  38. fileCreated, _ := os.Create("test2out.png")
  39. png.Encode(fileCreated, imageOut)
  40. }

输出的错误为:

  1. image: unknown format
kjthegm6

kjthegm61#

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

  1. image.DecodeConfig(file)

第二次在

  1. 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
一些快速和简单的你可以做的是打开文件两次

  1. file, err := os.Open("test2.png")
  2. if err != nil {
  3. fmt.Println("0 ", err)
  4. return
  5. }
  6. imageInConfig, _, err := image.DecodeConfig(file)
  7. if err != nil {
  8. fmt.Println("1 ", err)
  9. return
  10. }
  11. file2, err := os.Open("test2.png")
  12. if err != nil {
  13. fmt.Println("3 ", err)
  14. return
  15. }
  16. imageIn, _, err := image.Decode(file2)
  17. if err != nil {
  18. fmt.Println("4 ", err)
  19. return
  20. }

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

展开查看全部
ssgvzors

ssgvzors2#

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

  1. file.Seek(0, io.SeekStart)

相关问题