import imageio
from PIL import Image
import os
class Gif:
def __init__(self, img_dir, save_dir, gif_path):
self.img_dir = img_dir
self.save_dir = save_dir
self.gif_path = gif_path
self.img_paths = [os.path.join(self.img_dir, img_name) for img_name in os.listdir(self.img_dir)]
# 改变图片的尺寸
@staticmethod
def change_img_size(img_path, width, height, save_dir, save_path=None):
if not os.path.exists(save_dir):
os.makedirs(save_dir)
save_path = os.path.join(save_dir, os.path.basename(img_path)) if not save_path else save_path
img = Image.open(img_path)
out = img.resize((width, height), Image.ANTIALIAS)
out.save(save_path)
# 修改目录下所有的图片文件
def change_images_size(self):
width_height = [Image.open(img).size for img in self.img_paths]
width_list, height_list = [i[0] for i in width_height], [i[1] for i in width_height]
width_list.sort()
height_list.sort()
width_min = width_list[0]
height_min = height_list[0]
for img_path in self.img_paths:
self.change_img_size(img_path, width_min, height_min, self.save_dir)
# 制作Gif
def create_gif(self, image_list=None, duration=0.2, change_size=False):
if change_size:
self.change_images_size()
image_list = self.img_paths if not image_list else image_list
frames = [imageio.imread(image_name) for image_name in image_list]
imageio.mimsave(self.gif_path, frames, 'GIF', duration=duration)
if __name__ == '__main__':
gif = Gif(img_dir=r'photos', save_dir=r'new_photos', gif_path='xgx.gif')
gif.create_gif()
`