多张PNG合并成GIF

Washy
2025-05-23 / 0 评论 / 7 阅读 / 正在检测是否收录...

0 前言

最近的工作想生成一个GIF动画,但是使用python进行合并生成时,总是会遇到颜色失真的情况。百度+询问AI,给出了Pillow库和imageio库的方案,但不管如何调整参数都不会改善失真的情况。最终发现可以使用ffmpeg来解决,在此记录下。

1 安装ffmpeg

  • M1 Mac可以使用Homebrew工具直接安装(网络需要魔法),首先更新下Homebrew
brew update
brew upgrade
  • 安装ffmpeg
brew install ffmpeg
  • 等待安装结束后,使用如下命令打印版本号,输出版本号则安装成功
ffmpeg -version

2 编写Python脚本

  • 终端中调用ffmpeg不太方便,使用python编写一个脚本进行PNG图片合并,如下
# coding: utf-8
# author: Washy
# date: 2025/05/23

import os

# 将需要合并的图片路径按顺序存储
def pngfilepath2txt(filepath, txtfilepath='png2gif.txt'):
    # 列举指定目录下的所有png
    filePng = [item for item in os.listdir(filepath) if item.endswith('.png')]
    # 对png名称进行排序
    filePng = sorted(filePng)
    # 将路径存储为txt
    with open(txtfilepath, 'w') as f:
        for item in filePng:
            f.write(f"file '{filepath}/{item}'\n")

# 生成终端命令
def get_ffmpeg_cmd(fps, outfilepath, txtfilepath='png2gif.txt'):
    # 每秒帧数
    cmd0 = '-r %d ' % fps
    # concat
    cmd1 = '-f concat '
    # 需要处理的文件路径
    cmd2 = '-i %s ' % txtfilepath
    # 调色板
    cmd3 = '-filter_complex ' \
        + '"split[v1][v2]; [v1]palettegen[pal]; [v2][pal]paletteuse=dither=sierra2_4a" '
    # 输出文件名 - 重名自动覆盖
    cmd4 = outfilepath + ' -y'
    
    return 'ffmpeg ' + cmd0 + cmd1 + cmd2 + cmd3 + cmd4

# 主函数
def png2gif_main(pngfoldpath, giffilepath, fps=5, txtfilepath='png2gif.txt'):
    # 将png图片路径存储为txt
    pngfilepath2txt(pngfoldpath, txtfilepath)
    # 获取终端命令
    cmd = get_ffmpeg_cmd(fps, giffilepath, txtfilepath)
    try:
        # 运行终端命令
        os.system(cmd)
    except:
        raise Exception('ERROR: Create gif-file failed!')
    else:
        # 删除txt
        os.remove(txtfilepath)

if __name__=="__main__":
    # 待合并png存储文件夹
    pngfoldpath = "imgs/images"
    # 生成gif存储路径
    giffilepath = '01.gif'
    # 帧率
    fps = 5
    # 生成gif
    png2gif_main(pngfoldpath, giffilepath, fps)

3 效果展示

python库合并结果 ffmpeg合并结果
01.gif 02.gif

参考

0

评论 (0)

取消