加载特定PNG图片时触发Pillow的UnidentifiedImageError问题排查
Pillow加载PNG图片触发PIL.UnidentifiedImageError的排查方案
问题背景
加载特定PNG图片时触发PIL.UnidentifiedImageError,该图片可在浏览器正常打开,但其他图片能被Pillow正常解析,需定位问题原因。
错误片段
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x101c323b0>
复现代码
from PIL import Image import requests url = 'https://files.23point5.com/file?path=/artist-library/a39f0470-3cfe-4d5d-8288-ebf788c085c6.png' element_image = Image.open(requests.get(url, stream=True).raw) print(element_image)
核心原因及解决办法
请求返回非有效PNG数据
部分文件服务会根据请求头返回不同内容,浏览器能自动处理重定向、缺失头的情况,但requests默认请求可能拿到网页提示、未授权页面而非图片。可以先验证响应的内容类型,同时模拟浏览器请求头:from PIL import Image import requests from io import BytesIO headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36' } response = requests.get(url, headers=headers) # 先检查内容类型 if response.headers.get('Content-Type') != 'image/png': print(f"响应内容类型异常: {response.headers.get('Content-Type')}") # 可将内容保存为文件查看实际返回 with open('response_content.txt', 'wb') as f: f.write(response.content) else: img = Image.open(BytesIO(response.content)) print(img)图片格式存在Pillow不兼容的扩展
浏览器的图片解析引擎兼容性比Pillow更强,部分PNG可能使用了罕见的压缩算法或自定义扩展块,导致Pillow无法识别。解决办法是用图片编辑工具(如GIMP、Photoshop)将图片重新导出为标准PNG格式,再尝试加载。图片数据流未完整读取
使用stream=True直接调用response.raw可能导致数据未完全接收,Pillow无法解析不完整的图片流。改用读取完整内容到BytesIO的方式可以避免这个问题,代码如上所示。
内容的提问来源于stack exchange,提问作者Jay-R Joseph Gabunada
相关产品推荐
相关产品推荐

