【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}')
相关推荐
m0_748554817 小时前
golang如何实现用户订阅偏好管理_golang用户订阅偏好管理实现总结
jvm·数据库·python
smj2302_796826528 小时前
解决leetcode第3911题.移除子数组元素后第k小偶数
数据结构·python·算法·leetcode
阿正呀9 小时前
Redis怎样实现本地缓存的高效失效通知
jvm·数据库·python
九转成圣9 小时前
Java 性能优化实战:如何将海量扁平数据高效转化为类目字典树?
java·开发语言·json
SmartRadio9 小时前
ESP32-S3 双模式切换实现:兼顾手机_路由器连接与WiFi长距离通信
开发语言·网络·智能手机·esp32·长距离wifi
2501_901200539 小时前
mysql如何设置InnoDB引擎参数_优化innodb_buffer_pool
jvm·数据库·python
laowangpython9 小时前
Rust 入门:GitHub 热门内存安全编程语言
开发语言·其他·rust·github
我叫汪枫9 小时前
在后台管理系统中,如何递归和选择保留的思路来过滤菜单
开发语言·javascript·node.js·ecmascript
_.Switch9 小时前
东方财富股票数据JS逆向:secids字段和AES加密实战
开发语言·前端·javascript·网络·爬虫·python·ecmascript
软件技术NINI9 小时前
webkit简介及工作流程
开发语言·前端·javascript·udp·ecmascript·webkit·yarn