【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}')
相关推荐
不忘不弃17 分钟前
十进制数转换为二进制数
开发语言
likerhood37 分钟前
3. pytorch中数据集加载和处理
人工智能·pytorch·python
Data_agent1 小时前
京东图片搜索商品API,json数据返回
数据库·python·json
深盾科技1 小时前
融合C++与Python:兼顾开发效率与运行性能
java·c++·python
csbysj20201 小时前
jQuery Mobile 触摸事件
开发语言
代码村新手1 小时前
C++-入门
开发语言·c++
神舟之光1 小时前
VSCode编译运行C/C++程序问题及解决方法
开发语言·c++
坐怀不乱杯魂1 小时前
C++ STL unordered_map/set 实现
开发语言·c++
csbysj20201 小时前
jEasyUI 条件设置行背景颜色
开发语言
yaoh.wang1 小时前
力扣(LeetCode) 104: 二叉树的最大深度 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽