【问题标题】:How to Decode an image and keep the original in Go?如何解码图像并将原始图像保留在 Go 中?
【发布时间】:2021-12-19 19:57:14
【问题描述】:

我有以下代码:

imageFile, _ := os.Open("image.png") // returns *os.File, error

decodedImage, _, _ := image.Decode(imageFile) // returns image.Image, string, error
// imageFile has been modified!

当我在调用image.Decode 后尝试使用imageFile 时,它的行为不再相同,这让我相信image.Decode 以某种方式修改了imageFile

为什么image.Decode 修改原始值同时为decodedImage 返回一个新值 - 这不是误导吗?

如何保留原始值?有没有办法制作文件的“真实”副本,指向分配内存的新部分?

我刚开始使用 Go,如果我在这里遗漏了一些明显的东西,请道歉。

【问题讨论】:

  • 你是什么意思它被修改了?原始值是文件本身,所以如果要复制文件,则复制文件而不解码。
  • 我随后用imageFile 调用另一个函数。如果我在它不再识别文件之前调用了image.Decode。如果我在一切正常后调用它。
  • 再次打开或寻找开头。这与 Go 无关,它是文件的工作方式。

标签: go pointers


【解决方案1】:

问题中的代码没有修改磁盘上的文件。

图像解码后,imageFile 的当前位置在文件开头的某个位置。要再次读取文件,Seek 回到文件的开头:

 imageFile, err := os.Open("image.png")
 if err != nil { log.Fatal(err) }
 decodedImage, _, err := image.Decode(imageFile)
 if err != nil { log.Fatal(err) }

// Rewind back to the start of the file.
_, err := imageFile.Seek(0, io.SeekStart)
if err != nil { log.Fatal(err) }
// Do something with imageFile here.

log.Fatal 错误处理替换为适合您的应用程序的任何内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 2020-08-30
    • 2020-06-20
    • 2020-01-11
    • 2010-12-23
    • 1970-01-01
    相关资源
    最近更新 更多