如何在Go中解码图像并保留原始图像?

huangapple go评论71阅读模式
英文:

How to Decode an image and keep the original in Go?

问题

我有以下一段代码:

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

decodedImage, _, _ := image.Decode(imageFile) // 返回 image.Image, string, error
// imageFile 已经被修改了!

当我在调用 image.Decode 后尝试使用 imageFile 时,它不再表现出相同的行为,这让我相信 image.Decode 在某种程度上修改了 imageFile

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

如何保留原始值?有没有办法创建一个指向新分配内存的“真正”文件副本?

我刚开始学习 Go,如果我漏掉了一些显而易见的东西,请原谅。

英文:

I have the following bit of code:

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

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

When I try to work with imageFile after calling image.Decode it no longer behaves the same, leading me to believe image.Decode modified imageFile in some way.

Why is image.Decode modifying the original value while at the same time returning a new value for decodedImage - isn't this misleading?

How do I retain the original value? Is there a way to make a "real" copy of the file, pointing to a new part of allocated memory?

I just started out with Go, so apologies if I am missing something obvious here.

答案1

得分: 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) }

// 将文件指针回溯到文件开头。
_, err := imageFile.Seek(0, io.SeekStart)
if err != nil { log.Fatal(err) }
// 在这里对 imageFile 进行操作。

// 将 log.Fatal 错误处理替换为适合你的应用程序的处理方式。
英文:

The file on disk is not modified by the code in the question.

The current position of imageFile is somewhere past the beginning of the file after the image is decoded. To read the fie again, Seek back the beginning of the file:

 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.

Replace the log.Fatal error handling with whatever is appropriate for your application.

huangapple
  • 本文由 发表于 2021年11月6日 04:05:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/69858711.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定