You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PIL保存图片遇struct.error:如何捕获并处理该异常?

处理PIL保存图片时的struct.error异常问题

问题背景

使用PIL批量处理图片:打开图片读取EXIF信息,压缩到指定大小后保存时重新写入原EXIF。处理约3000个文件后,某张图片在执行img.save步骤时抛出异常:struct.error: 'H' format requires 0 <= number <= 65535,推测是原图片的EXIF格式不符合PIL的预期要求。

尝试通过try-except捕获该异常时,出现NameError: name 'struct' is not defined错误,无法正常执行降级逻辑(不带EXIF保存)。

解决方法

1. 导入struct模块

异常类型struct.error属于Python标准库的struct模块,必须先导入该模块才能捕获对应异常,否则会触发NameError。

2. 修正异常捕获代码

调整try-except代码块,优先尝试带EXIF保存,触发struct.error时则跳过EXIF直接保存。

完整修正代码示例

import os
import struct
from PIL import Image, ExifTags

allowed_size = 123456  # 允许的目标文件大小
fname = 'path/to/file.type'
file_size = os.path.getsize(fname)
new_fname = 'path/to/new_compressed.jpg'  # 替换为实际的新文件路径

img = Image.open(fname)
exif = img.getexif()
upload_size = allowed_size  # 根据实际业务逻辑调整变量赋值

if len(exif) > 0:
    if file_size > upload_size:
        try:
            # 优先尝试保留EXIF保存
            img.save(new_fname, "JPEG", optimize=True, quality=100, exif=exif)
        except struct.error:
            # 捕获到EXIF格式错误时,不带EXIF保存
            img.save(new_fname, "JPEG", optimize=True, quality=100)
        # 后续的图片缩放等操作

补充说明

触发struct.error的核心原因是原图片的EXIF中存在不符合JPEG EXIF规范的字段(比如某个字段的值超出了H格式(无符号短整型)的取值范围0~65535),导致PIL在序列化EXIF数据时失败。通过捕获该异常并降级保存,可以避免批量处理流程中断。

内容的提问来源于stack exchange,提问作者Alex Haeger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 14:57:36