Windows11下使用PIL.Image打开图片遇UnidentifiedImageError求助
使用PIL打开PNG图片遭遇
UnidentifiedImageError的问题解决 问题场景
执行PIL.Image.open()时触发识别错误,操作及报错详情如下:
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'
已确认文件真实存在且可手动打开,路径中的双反斜杠是Windows系统标准路径表示,排除路径格式问题。
图片有效性验证
读取文件前100字节确认PNG格式合法性:
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"
分析与解决方法
从文件头\x89PNG\r\n\x1a\n可判断,这是标准合法的PNG文件。问题根源在于该图片携带了Exif元数据(输出中的zTXtRaw profile type exif字段),部分旧版本PIL对这类带额外元数据的PNG存在解析兼容问题。
可采用以下方案解决:
- 升级PIL到最新版本:执行命令
pip install --upgrade pillow,新版本修复了大量元数据解析相关的bug。 - 手动指定图片格式:强制PIL以PNG格式解析文件,绕过自动检测逻辑:
from PIL import Image img = Image.open(picpath, formats=["PNG"]) - 通过二进制文件对象打开:先以二进制模式读取文件,再传入PIL处理:
from PIL import Image with open(picpath, "rb") as f: img = Image.open(f) img.load() # 确保完成图片数据加载
内容的提问来源于stack exchange,提问作者alxmke
相关产品推荐
相关产品推荐

