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

统计TIFF文件页数触发TypeError: int()参数类型错误

TIFF图片页数统计遇损坏文件报错的解决方法

问题背景

我需要统计TIFF格式图片的页数,写了如下代码:

from pathlib import Path
from PIL import Image
import os

def count_pages(img):
    i = 0                                                                           
    while True:
        try:   
            img.seek(i)
        except EOFError:
            break       
        i += 1          
    return i

BASE_DIR = Path.cwd()
IDs_DIR = BASE_DIR / 'FLDR'
sPath = os.path.join(IDs_DIR, 'ggg.tiff')    
im = Image.open(sPath)
print(count_pages(im))

但部分TIFF文件运行时触发错误,报错信息如下:

site-packages\PIL\TiffImagePlugin.py:845: UserWarning: Corrupt EXIF data.  Expecting to read 2 bytes but only got 0.
  warnings.warn(str(msg))
Traceback (most recent call last):
  File "Demo.py", line 19, in <module>
    print(count_pages(im))
  File "Demo.py", line 9, in count_pages
    img.seek(i)
  File "C:\Users\Future\AppData\Local\Programs\Python\Python38\lib\site-packages\PIL\TiffImagePlugin.py", line 1101, in seek
    self._seek(frame)
  File "C:\Users\Future\AppData\Local\Programs\Python\Python38\lib\site-packages\PIL\TiffImagePlugin.py", line 1142, in _seek
    self._setup()
  File "C:\Users\Future\AppData\Local\Programs\Python\Python38\lib\site-packages\PIL\TiffImagePlugin.py", line 1333, in _setup
    xsize = int(self.tag_v2.get(IMAGEWIDTH))
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

解决办法

方法1:修改现有代码,捕获损坏帧异常

报错根源是损坏TIFF帧的IMAGEWIDTH标签值为None,导致int()转换失败。可以在count_pages函数中额外捕获TypeError,跳过损坏帧继续统计:

from pathlib import Path
from PIL import Image
import os

def count_pages(img):
    i = 0                                                                           
    while True:
        try:   
            img.seek(i)
            img.load()  # 强制加载帧数据,确保检测到损坏
        except EOFError:
            break
        except TypeError:
            # 遇到损坏帧,跳过并继续统计
            i += 1
            continue       
        i += 1          
    return i

BASE_DIR = Path.cwd()
IDs_DIR = BASE_DIR / 'FLDR'
sPath = os.path.join(IDs_DIR, 'ggg.tiff')    
im = Image.open(sPath)
print(count_pages(im))

方法2:换用tifffile库(兼容性更好)

如果PIL的处理方式仍有问题,可以用tifffile库——它直接解析TIFF文件结构,不需要加载每帧数据,对损坏文件的兼容性更强。

首先安装库:

pip install tifffile

然后替换代码:

from pathlib import Path
import tifffile

BASE_DIR = Path.cwd()
IDs_DIR = BASE_DIR / 'FLDR'
sPath = IDs_DIR / 'ggg.tiff'    

with tifffile.TiffFile(sPath) as tif:
    print(len(tif.pages))

可选:关闭EXIF警告

如果不想看到EXIF损坏的警告信息,可以在代码开头添加:

import warnings
warnings.filterwarnings("ignore", category=UserWarning, module="PIL")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 03:05:19