首先是导入需要的库:
'''
快速制作GIF图片
'''
import os
import PIL.Image as Image
import imageio
思路:
第一步:整理出我们需要的图片(图片格式处理,个人选择)
'''传入放着图片的文件夹路径'''
def get_img(paths):
images = []
#判断文件夹中,我们需要添加的图片格式,获取图片列表
if os.path.exists(paths):
file_img = os.listdir(paths)
print(file_img)
for i in file_img:
if ".png" in i or ".jpg" in i:
images.append(i)
return images
第二步:处理图片的分辨率大小。(统一分辨率,否则,GIF图片大小显示不对齐)
'''#统一分辨率'''
def resize_image(path,files):
# 获取输入文件夹中的所有文件
output_dir = r"D:\Python_studyltem\Python_get_GIF\picture"
# 判断输出文件夹是否存在,不存在则创建
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for file in files:
img = Image.open(path +"\\"+ file)
if img.mode == "P":
img = img.convert('RGB')
if img.mode == "RGBA":
img = img.convert('RGB')
#img.resize((700, 500),Image.ANTIALIAS))设置图片的分辨率
img = img.resize((700, 500), Image.ANTIALIAS)
img.save(os.path.join(output_dir, file))
print(str(file) + " :图片分辨率更改成功!")
return output_dir
第三步:传入修改分辨率后的图片至创建GIF的函数。
'''创作GIF图片'''
def create_gif(images, gif_name, duration,paths):
frames = []
path = paths.split("\\")
for image_name in images:
frames.append(imageio.imread(path[-1]+"\\{}".format(image_name))) #传递图片路径给画面
imageio.mimsave(gif_name, frames, 'GIF', duration=duration)
主程序代码如下:(其中路径,如需使用程序,需自行设置。)
# _*_ coding=utf-8 _*_
'''
快速制作GIF图片
'''
import os
import PIL.Image as Image
import imageio
'''创作GIF图片'''
def create_gif(images, gif_name, duration,paths):
frames = []
path = paths.split("\\")
for image_name in images:
frames.append(imageio.imread(path[-1]+"\\{}".format(image_name))) #传递图片路径给画面
imageio.mimsave(gif_name, frames, 'GIF', duration=duration)
'''#统一分辨率'''
def resize_image(path,files):
# 获取输入文件夹中的所有文件
output_dir = r"D:\Python_studyltem\Python_get_GIF\picture"
# 判断输出文件夹是否存在,不存在则创建
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for file in files:
img = Image.open(path +"\\"+ file)
if img.mode == "P":
img = img.convert('RGB')
if img.mode == "RGBA":
img = img.convert('RGB')
img = img.resize((700, 500), Image.ANTIALIAS)
img.save(os.path.join(output_dir, file))
print(str(file) + " :图片分辨率更改成功!")
return output_dir
'''传入放着图片的文件夹路径'''
def get_img(paths):
images = []
#判断文件夹中,我们需要添加的图片格式,获取图片列表
if os.path.exists(paths):
file_img = os.listdir(paths)
print(file_img)
for i in file_img:
if ".png" in i or ".jpg" in i:
images.append(i)
return images
#1、==========================
paths = r"D:\Python_studyltem\Python_get_GIF\imgfile"
'''
识别出个人需要的图片格式
'''
images = get_img(paths)
#2、==========================
'''
修改图片的分辨率
paths:传入图片的路径
images:个人需要的图片名称
'''
new_path = resize_image(paths,images)
#3、==========================
'''
new_path:修改分辨率后的图片的存放路径
'''
imageh = get_img(new_path)
#4、==========================
'''
备注:
imageh:即是传递需要融合在一起的图片,
test.gif:保存的图片名称
duration:图片之间跳动时间的间隔
paths:
'''
create_gif(imageh, 'test.gif', duration=0.5,paths=new_path)
#==========================