打开PNG失败,并显示"无法识别图像文件"



我正在尝试用Python打开一个PNG文件。我相信我有一个正确编码的PNG。

它开始于:

x89PNGrnx1anx00x00x00rIHDR 

以结尾

x00IENDxaeB`x82

到目前为止我的代码:

import PIL.Image as Image
with open('./test_image_3.txt', 'rb') as f:
b = f.read()
b = base64.b64decode(b).decode("unicode_escape").encode("latin-1")
b = b.decode('utf-16-le')
img = Image.open(io.BytesIO(b))
img.show()
b = base64.b64decode(b).decode("unicode_escape").encode("latin-1")
UnicodeDecodeError: 'unicodeescape' codec can't decode bytes in position 178-179: truncated uXXXX escape

不幸的是,我无法阅读您提供的文件,因为网站对它进行了大量屠杀。使用pastebin或github(或类似的东西(,在那里可以检索text/plain,例如通过curl,这样我就可以尝试为内容1:1再现问题。

然而,一般的方法是:

from PIL import Image
with Image.open("./test_image_3.txt") as im:
im.show()

它直接来自Pillow的文档,它不关心文件的名称或扩展名。

或者,如果您有带有文件句柄的open()调用:

from PIL import Image
with open("./test_image_3.txt", "rb") as file:
with Image.open(file) as im:
im.show()

如果你以某种方式破坏了它,那么从你的encode()decode()调用来看,它应该是这样的:

from PIL  import Image
from io import BytesIO
data = <some raw PNG bytes, the original image>
# here I store it in that weird format and write as bytes
with open("img.txt", "wb") as file:
file.write(data.decode("latin-1").encode("unicode_escape"))
# here I read it back as bytes, reverse the chain of calls and invert
# the call pairs for en/decoding so encode() -> decode() and vice-versa
with open("img.txt","rb") as file:
content = BytesIO()
content.write(
file.read().decode("unicode_escape").encode("latin-1")
)
# seek back, so the BytesIO() can return back the full content
content.seek(0)
# then simply read as if using a file handle
with Image.open(content) as img:
img.show()

最新更新