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

使用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

关键修复点

  1. 所有路径转字符串:temp_image_path、image_source_path、source_path以及get_image_sequence_frame_count中的image_path都用str()包裹,确保传入PIL的是字符串类型。
  2. 显式指定保存格式:在frame_copy.save()中添加format='TIFF',避免PIL自动推断格式时传入不符合要求的参数。
  3. 保留临时文件策略:直接追加到源文件会覆盖第一帧,是因为源文件未以正确的追加模式打开,当前的临时文件中转方案是合理的,无需修改。

额外检查项

  • 确认TEMP_IMG目录已存在,可提前执行TEMP_IMG.mkdir(exist_ok=True)避免目录不存在错误。
  • 检查第12个待追加文件的路径是否存在特殊字符或权限问题,排除文件本身的异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 22:39:19