在 Windows 11 上使用 PIL.Image 打开图像文件时出现问题

问题描述 投票:0回答:1

我尝试使用

PIL.Image
打开图像,但遇到此错误:

Python 3.11.4 (tags/v3.11.4:d2340ef, Jun  7 2023, 05:45:37) [MSC v.1934 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.listdir(".")
['Characters', 'Creatures', 'processing.ipynb']
>>> picpath = os.path.join("Characters", "4sprite", "Female_Archer", "Archer_Base", "Sprite_1.png")
>>> os.path.exists(picpath)
True
>>> from PIL import Image
>>> img = Image.open(picpath)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Alex\AppData\Local\Programs\Python\Python311\Lib\site-packages\PIL\Image.py", line 3305, in open
    raise UnidentifiedImageError(msg)
PIL.UnidentifiedImageError: cannot identify image file 'Characters\\4sprite\\Female_Archer\\Archer_Base\\Sprite_1.png'

我现在最好的猜测是,它与

PIL
在 Windows 上处理路径的方式有关,因为
os.path.exists
找到了该文件(并且我已经手动验证了该文件存在并且可以打开和查看)。我注意到该路径有双反斜杠,但我发现的 resources 说这是规范的表示。我看到有人遇到了类似的问题,但不幸的是他们的解决方案是使用
PIL.Image.open
(这就是给我抛出错误的原因)。

还有其他人遇到过并解决过这个问题吗?


问:Sprite_1.png 是什么类型的图像(编码、通道数和大小)?它实际上是具有有效格式的 PNG 吗?你能告诉我们前一百个字节吗? – 布莱恩61354270

答:

with open(os.path.join("Characters", "4sprite", "Female_Archer", "Archer_Base", "Sprite_1.png"), "rb") as f:
     first_100 = f.read(100)
print(first_100)

给予

b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x0f\x00\x00\x00\x0f\xa0\x08\x06\x00\x00\x00G'\xe9\xd3\x00\x00a.zTXtRaw profile type exif\x00\x00x\xda\xac\xbdY\x92\xc48\xb6m\xf7\xcfQ\xbc!\x10=8\x1c\x00$\xcc4\x03\r_k\xc1#\xab\xea\xdew%3\xc9"

python python-3.x windows image runtime-error
1个回答
0
投票

似乎有几种可能性:

  • PIL 无法理解文件的路径,或者
  • PIL 可以理解文件的路径,但无法理解其内容。

共享文件,使用 Dropbox/Github/Google Drive 或其他不更改文件的服务会有所帮助。

要检查第一种可能性,您可以自己读取该文件并将其传递给 PIL,这样 PIL 就不必处理您的路径。事情会是这样的:

# Slurp entire file
with open(os.path.join("Characters", "4sprite", "Female_Archer", "Archer_Base", "Sprite_1.png"), "rb") as f:
    data = f.read()

from io import BytesIO

# Wrap bytes in a BytesIO and pass to PIL
im = Image.open(BytesIO(data))

如果有效,则意味着 PIL 可以理解文件内容,但无法通过您的路径访问它们。如果不起作用,则表明您的文件内容存在问题,您需要共享它。

© www.soinside.com 2019 - 2024. All rights reserved.