【python】Python生成GIF动图,多张图片转动态图,pillow

pip install pillow

示例代码:

python 复制代码
from PIL import Image, ImageSequence

# 图片文件名列表
image_files = ['car.png', 'detected_map.png', 'base64_image_out.png']

# 打开图片
images = [Image.open(filename) for filename in image_files]

# 设置输出 GIF 文件名
output_gif = 'output.gif'

# 将图片保存为 GIF
images[0].save(
    output_gif,
    save_all=True,
    append_images=images[1:],
    duration=2000,  # 设置每张图片的显示时间(毫秒)
    loop=0,  # 设置循环次数,0 表示不循环
)

print(f'GIF 文件已创建: {output_gif}')

将某个路径的所有图片按名称排序后,转为gif文件:

clike 复制代码
import os
from PIL import Image, ImageSequence

# 目标路径
target_path = './images'

# 获取目录下所有文件
all_files = os.listdir(target_path)

# 筛选出图片文件
image_files = [os.path.join(target_path, filename) for filename in all_files if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif'))]

# 按照文件名排序
sorted_image_files = sorted(image_files)

# 打开图片并调整为相同的模式
images = [Image.open(filename).convert('RGBA') for filename in sorted_image_files]

# 设置输出 GIF 文件名
output_gif = 'output.gif'

# 将图片保存为 GIF
images[0].save(
    output_gif,
    save_all=True,
    append_images=images[1:],
    duration=2000,  # 设置每张图片的显示时间(毫秒)
    loop=0,  # 设置循环次数,0 表示不循环
)

print(f'GIF 文件已创建: {output_gif}')
相关推荐
这里有鱼汤1 小时前
miniQMT下载历史行情数据太慢怎么办?一招提速10倍!
前端·python
databook10 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室10 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三12 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户25191624271115 小时前
Python之语言特点
python
刘立军16 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机19 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机20 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i21 小时前
django中的FBV 和 CBV
python·django
c8i1 天前
python中的闭包和装饰器
python