Python 批量处理图片,生成gif动图

Python015

Python 批量处理图片,生成gif动图,第1张

大多博客给的生成GIF图都是要手打图片名字,觉得太麻烦,整了个把所有图片放在一个文件夹里,就可以就这些图片生成GIF图的工具

# user:Yollison

# Author: Yollison

# createtime: 2021/9/23 9:41

'''

这个程序是把某个文件夹里所有图片生成GIF动图

里面的功能不包括整理图片格式,直接暴力生成,所以图片最好在保存时就整理好格式

'''

import imageio

import os

def create_gif(image_list, gif_name, duration=0.35):

frames = []

for image_namein image_list:

frames.append(imageio.imread(image_name))

imageio.mimsave(gif_name, frames, 'GIF', duration=duration)

return

def main():

image_list = []

# 自动读取文件夹里图片的名字

    for filenamein os.listdir(r"D:/results"):# 图片所在文件夹的路径

        image_list.append('D:\\results\\'+filename)# 此路径与上一条语句路径保持一致

    gif_name ='result.gif' # 保存路径在此程序这里,也可自己指定路径

    duration =0.35

    # 生成gif

    create_gif(image_list, gif_name, duration)

if __name__ =='__main__':

main()

解决这个问题需要用到PIL库

from PIL import Image

import os

第一步 获得所有图像文件列表,过滤不需要扩展名

filelist = []  

path = os.getcwd()

files = os.listdir(path)

for f in files:  

    if(os.path.isfile(path + '/' + f)):

        if (os.path.splitext(f)[1] == ".BMP"):

            filelist.append(f)

        if (os.path.splitext(f)[1] == ".JPG"):

            filelist.append(f)

        if (os.path.splitext(f)[1] == ".PNG"):

            filelist.append(f)

        if (os.path.splitext(f)[1] == ".TIF"):

            filelist.append(f)

第二步 当判断文件不是GIF格式的时候转换为GIF格式

for infile in filelist:

  outfile = os.path.splitext(infile)[0] + ".gif"

  if infile != outfile:

    try:

      Image.open(infile).save(outfile)

      print "Covert to GIF successfully!"

    except IOError:

      print "This format can not support!", infile