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

Python中PIL读取动图WebP无法获取帧时长问题求助

解决PIL无法获取WebP动图帧时长的问题

问题根源

PIL的WebP解码器对部分动图的元数据解析支持不足,导致无法提取帧时长信息,仅能读取Loop、background这类基础属性。

可行解决方案

方案1:用pywebp精准解析WebP元数据

pywebp是专门针对WebP格式开发的库,能准确读取动图的帧时长:

  1. 安装依赖:
pip install pywebp
  1. 解析帧时长的代码示例:
from webp import WebP

def get_webp_frame_durations(file_path):
    with open(file_path, 'rb') as f:
        webp_data = f.read()
    webp = WebP(webp_data)
    if webp.is_animated:
        return [frame.duration for frame in webp.frames]
    return []

拿到帧时长列表后,你可以自行计算帧率,或者在保存GIF时为每帧指定对应延迟。

方案2:用imageio一站式处理转格式与帧率读取

imageio对动图格式的兼容性更强,能直接获取帧率并完成格式转换:

  1. 安装依赖(需带ffmpeg支持):
pip install imageio[ffmpeg]
  1. 转换代码示例:
import imageio

def convert_webp_to_gif(input_path, output_path):
    reader = imageio.get_reader(input_path)
    fps = reader.get_meta_data()['fps']
    writer = imageio.get_writer(output_path, fps=fps)
    
    for frame in reader:
        writer.append_data(frame)
    writer.close()

该方法无需手动计算帧率,直接完成WebP到GIF的转换,同时保留原动图的帧率。

方案3:升级Pillow尝试修复

如果你想继续使用PIL,先升级到最新版本,新版本可能修复了部分WebP解析的bug:

pip install --upgrade pillow

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 02:23:12