Python读取zip包内图片时抛出PIL.UnidentifiedImageError错误如何解决?
问题排查与解决
报错核心原因
ZipFile.namelist()会返回压缩包内所有条目,包括子文件夹路径,读取文件夹得到的空字节流无法被PIL识别为图片- 压缩包内可能存在非图片格式文件、损坏的图片文件,或是你的Pillow版本不支持对应图片格式(如webp、heic等格式需要额外依赖或高版本Pillow)
- 部分图片可能是无扩展名的伪装文件,实际不属于PIL支持的图像类型
修复代码
import zipfile from PIL import Image from PIL.ExifTags import TAGS from io import BytesIO # 支持的图片后缀,可根据实际需求扩展 SUPPORTED_EXT = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'} with zipfile.ZipFile("samples.zip", "r") as f: # 用infolist替代namelist,方便直接判断是否为文件夹 for info in f.infolist(): # 跳过文件夹条目 if info.is_dir(): continue # 转小写判断后缀,避免大小写问题 file_ext = info.filename.rsplit('.', 1)[-1].lower() if '.' in info.filename else '' if f'.{file_ext}' not in SUPPORTED_EXT: print(f"跳过非图片文件:{info.filename}") continue try: image_data = f.read(info.filename) image = Image.open(BytesIO(image_data)) # 验证图片有效性,部分损坏图片open不会报错,load才会触发异常 image.verify() # 验证后需要重新打开,verify操作会重置文件指针 image = Image.open(BytesIO(image_data)) exif_data = image.getexif() width, height = image.size print(f"{info.filename} 尺寸:{width}x{height}") except Exception as e: print(f"处理文件{info.filename}失败:{str(e)}")
额外优化建议
- 如果使用的Pillow版本较低,可执行
pip install --upgrade pillow升级到最新版本,支持更多图片格式 - 若需要处理heic等特殊格式,需要额外安装对应依赖,比如heic格式需安装
pillow-heif库
内容的提问来源于stack exchange,提问作者Imane Mamri
相关产品推荐
相关产品推荐

