I encountered a certain problem with corrupt .png
image files* that I was able to overcome by simply opening them in an image editor (Apple's Preview) and saving them back, without making any explicit changes.
I have thousands of similarly corrupt image files that need to be subjected to the same procedure. Is there a way to automate it in python?
The following naive code doesn't work:
>>> with open('an_image.png', 'rb') as f:
... data = f.read()
... with open('an_image.png', 'wb') as f:
... f.write(data)
Why doesn't this code work? What does the image editor do that corrects the problem, and how can I imitate it programmatically?
My operating system is macOS Sierra Version 10.12.4.
My python version is 3.6.1.
Here is an example of one of the corrupt files.
* For those interested, the original problem is described here.
Your example file, https://i.stack.imgur.com/a5uXX.png, isn't actually a PNG file. It's a "CgBI" file instead, which is a PNG-like file created by Apple X-code software, probably using their rogue "pngcrush" application. There are various ways of recovering a valid PNG file from a CgBI file (except for unavoidable loss of precision in the underlying color values of non-opaque pixels).
The Apple-modified pngcrush is itself capable of reverting the "iPhone optimizations"
There are third-party applications such as the public domain, open source pngdefry application that can be found on the net.
Apologies for not showing you how to invoke pngdefry or pngcrush via python calls, but hopefully this will set you on the right track, and at least tell you what has happened to your files.
Legal Notice: I am required to note that Apple and iPhone are registered trademarks of Apple, Inc.