【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}')
相关推荐
weixin_46244623几秒前
【原创实践】Python 将 Markdown 文件转换为 Word(docx)完整实现
开发语言·python·word
企微自动化4 分钟前
企业微信二次开发:深度解析外部群主动推送的实现路径
java·开发语言·企业微信
我的offer在哪里10 分钟前
c++的回调函数
开发语言·c++
智航GIS11 分钟前
ArcGIS大师之路500技---048计算流水号
python·arcgis
一棵开花的树,枝芽无限靠近你13 分钟前
【face-api.js】2️⃣ NetInput - 神经网络输入封装类
开发语言·javascript·神经网络
yongche_shi13 分钟前
第九十九篇:Python在其他领域的应用:游戏开发、物联网、AIoT简介
开发语言·python·物联网·游戏开发·aiot
froginwe1114 分钟前
Node.js 回调函数
开发语言
期待のcode17 分钟前
Java中的继承
java·开发语言
资深低代码开发平台专家17 分钟前
MicroQuickJS:为极致资源而生的嵌入式JavaScript革命
开发语言·javascript·ecmascript
世转神风-18 分钟前
qt-通信协议基础-固定长度-小端字节序补0x00指导
开发语言·qt