使用PIL拼接TIFF帧时遇TypeError:参数5需为str而非PosixPath
解决TIFF帧追加时的TypeError: argument 5 must be str, not PosixPath
问题根源
报错是因为TiffImagePlugin.AppendingTiffWriter的底层实现要求路径参数为字符串,代码中直接传入了PosixPath对象,即便部分转换,仍有遗漏的Path对象传入编码器触发错误。
修复代码
修改所有路径相关参数,强制转换为字符串,并在保存时显式指定格式:
from PIL import Image, ImageSequence, TiffImagePlugin from pathlib import Path def insert_into_tiff(image_source_path, passed_images, delete_file=False, delete_converted=True): # 将临时路径转为字符串 temp_image_path = str(TEMP_IMG / f'temp_{Path(image_source_path).name}') with TiffImagePlugin.AppendingTiffWriter(temp_image_path, True) as image_to_be_appended: append_tiff_sequences(str(image_source_path), image_to_be_appended) for p in passed_images: source_path = str(TEMP_IMG / p['new_name']) append_tiff_sequences(source_path, image_to_be_appended) def append_tiff_sequences(image_source_path, image_to_be_appended): frame_count = get_image_sequence_frame_count(image_source_path) print(f"append {frame_count} frames from {image_source_path}") with Image.open(image_source_path) as additional_images: for frame in ImageSequence.Iterator(additional_images): frame_copy = frame.copy() # 显式指定保存格式为TIFF,避免格式推断错误 frame_copy.save(image_to_be_appended, format='TIFF') image_to_be_appended.newFrame() frame_copy.close() def get_image_sequence_frame_count(image_path): # 这里也需要将路径转为字符串 return Image.open(str(image_path)).n_frames
关键修复点
- 所有路径转字符串:
temp_image_path、image_source_path、source_path以及get_image_sequence_frame_count中的image_path都用str()包裹,确保传入PIL的是字符串类型。 - 显式指定保存格式:在
frame_copy.save()中添加format='TIFF',避免PIL自动推断格式时传入不符合要求的参数。 - 保留临时文件策略:直接追加到源文件会覆盖第一帧,是因为源文件未以正确的追加模式打开,当前的临时文件中转方案是合理的,无需修改。
额外检查项
- 确认
TEMP_IMG目录已存在,可提前执行TEMP_IMG.mkdir(exist_ok=True)避免目录不存在错误。 - 检查第12个待追加文件的路径是否存在特殊字符或权限问题,排除文件本身的异常。
内容的提问来源于stack exchange,提问作者ron_g
相关产品推荐
相关产品推荐

