python 打开PNG失败,原因是“无法识别图像文件”

ddhy6vgd  于 2023-01-01  发布在  Python
关注(0)|答案(1)|浏览(746)

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

\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR

结尾为:

\x00IEND\xaeB`\x82

我的代码到目前为止:
一个二个一个一个

rkue9o1l

rkue9o1l1#

不幸的是,我无法阅读你提供的文件,因为网站已经将其大量拆分。使用pastebin或github(或类似的工具),可以检索text/plain,例如通过curl,这样我就可以尝试1:1重现问题的内容。
但是,一般的做法是:

from PIL import Image

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

它直接来自Pillow的documentation,不关心文件名或扩展名。
或者,如果您使用文件句柄调用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()

相关问题