首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python -打开一个PNG失败了‘不能识别图像文件’

Python -打开一个PNG失败了‘不能识别图像文件’
EN

Stack Overflow用户
提问于 2022-02-23 17:59:30
回答 1查看 314关注 0票数 0

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

文件全文:https://ctxt.io/2/AABgnYYrEw

它的开头是:

代码语言:javascript
运行
复制
\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR 

并以以下内容结束:

代码语言:javascript
运行
复制
\x00IEND\xaeB`\x82

到目前为止我的代码是:

代码语言:javascript
运行
复制
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")
代码语言:javascript
运行
复制
    UnicodeDecodeError: 'unicodeescape' codec can't decode bytes in position 178-179: truncated \uXXXX escape
EN

回答 1

Stack Overflow用户

发布于 2022-02-23 20:00:23

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

然而,一般的做法是:

代码语言:javascript
运行
复制
from PIL import Image

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

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

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

代码语言:javascript
运行
复制
from PIL import Image

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

如果你把它弄坏了,那么从你的encode()decode()调用来看,会是这样的:

代码语言:javascript
运行
复制
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()
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71241944

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档