Home > Back-end >  How to Decode an image and keep the original in Go?
How to Decode an image and keep the original in Go?

Time:11-06

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.

CodePudding user response:

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.

  • Related