【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}')
相关推荐
曲幽4 小时前
FastAPI + PostgreSQL 实战:从入门到不踩坑,一次讲透
python·sql·postgresql·fastapi·web·postgres·db·asyncpg
用户8356290780518 小时前
使用 C# 在 Excel 中创建数据透视表
后端·python
码路飞11 小时前
FastMCP 实战:一个 .py 文件,给 Claude Code 装上 3 个超实用工具
python·ai编程·mcp
dev派13 小时前
AI Agent 系统中的常用 Workflow 模式(2) Evaluator-Optimizer模式
python·langchain
前端付豪15 小时前
AI 数学辅导老师项目构想和初始化
前端·后端·python
用户03321266636715 小时前
将 PDF 文档转换为图片【Python 教程】
python
悟空爬虫17 小时前
UV实战教程,我啥要从Anaconda切换到uv来管理包?
python
dev派17 小时前
AI Agent 系统中的常用 Workflow 模式(1)
python·langchain
明月_清风19 小时前
从“能用”到“专业”:构建生产级装饰器与三层逻辑拆解
后端·python
曲幽1 天前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic