我试图用Python打开一个PNG文件。我相信我有一个正确编码的PNG。
文件全文:https://ctxt.io/2/AABgnYYrEw
它的开头是:
\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR
并以以下内容结束:
\x00IEND\xaeB`\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
发布于 2022-02-23 20:00:23
不幸的是,我无法阅读你提供的文件,因为网站对它进行了大量的屠杀。可以使用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()
https://stackoverflow.com/questions/71241944
复制相似问题