Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Decode an image and keep the original in 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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading