简体   繁体   English

如何使用python模仿在图像编辑器中打开和保存图像文件?

[英]How to use python to imitate the opening and saving of an image file in an image editor?

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. 我遇到了损坏的.png图像文件*的某个问题,只需在图像编辑器(Apple的Preview )中打开它们并将其保存回去,而无需进行任何显式更改,就可以解决。

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? 有没有办法在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. 我的操作系统是macOS Sierra版本10.12.4。
My python version is 3.6.1. 我的python版本是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. 您的示例文件https://i.stack.imgur.com/a5uXX.png实际上不是PNG文件。 It's a "CgBI" file instead, which is a PNG-like file created by Apple X-code software, probably using their rogue "pngcrush" application. 取而代之的是“ CgBI”文件 ,这是由Apple X代码软件创建的类似PNG的文件,可能使用了他们的流氓“ pngcrush”应用程序。 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). 有多种方法可以从CgBI文件中恢复有效的PNG文件(除非不可避免地会损失非透明像素的基础颜色值的精度)。

  • The Apple-modified pngcrush is itself capable of reverting the "iPhone optimizations" 苹果修改的pngcrush本身具有还原“ iPhone优化”的功能

  • There are third-party applications such as the public domain, open source pngdefry application that can be found on the net. 在网上可以找到第三方应用程序,例如公共领域,开源pngdefry应用程序。

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. 很抱歉没有向您展示如何通过python调用来调用pngdefry或pngcrush,但希望这能使您走上正确的轨道,至少可以告诉您文件发生了什么。

Legal Notice: I am required to note that Apple and iPhone are registered trademarks of Apple, Inc. 法律声明:我需要注意Apple和iPhone是Apple,Inc.的注册商标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM