layout: posttitle: Python3 实现 gif 倒放,多张图片生成 gif
subtitle: Python3 实现 gif 倒放,多张图片生成 gif
date: 2019-12-15
author: he xiaodong
header-img: img/default-post-bg.jpg
catalog: true
tags:
- python3
- PTL
- imageio
- gif倒放
- reverse gif
- generate gif
- python 合并图片成 gif

一个娱乐代码,将表情包 gif 倒放很搞笑,当成自己的一个小玩具,操作就是将图片读取成帧,倒排合并一下,成为新的图片,完成。

效果:翻转前 2019-12-15-Python3 实现倒放 gif 图片 多张图片生成gif - 图1 翻转后 2019-12-15-Python3 实现倒放 gif 图片 多张图片生成gif - 图2

代码如下:

  1. # encoding: utf-8
  2. from PIL import Image, ImageSequence
  3. # 读取GIF
  4. im = Image.open("nba.gif")
  5. # GIF图片流的迭代器
  6. iter = ImageSequence.Iterator(im)
  7. index = 1
  8. # 遍历图片流的每一帧
  9. for frame in iter:
  10. print("image %d: mode %s, size %s" % (index, frame.mode, frame.size))
  11. frame.save("./images/frame%d.png" % index)
  12. index += 1
  13. # frame0 = frames[0]
  14. # frame0.show()
  15. # 把GIF拆分为图片流
  16. imgs = [frame.copy() for frame in ImageSequence.Iterator(im)]
  17. # 把图片流重新成成GIF动图
  18. # imgs[0].save('out.gif', save_all=True, append_images=imgs[1:])
  19. # 图片流反序
  20. imgs.reverse()
  21. # 将反序后的所有帧图像保存下来
  22. imgs[0].save('./reverse_out.gif', save_all=True, append_images=imgs[1:])

另外极简版更简单

  1. # encoding: utf-8
  2. from PIL import Image, ImageSequence
  3. im = Image.open(r'./nba.gif')
  4. sequence = []
  5. for f in ImageSequence.Iterator(im):
  6. sequence.append(f.copy())
  7. sequence.reverse()
  8. sequence[0].save(r'./r-nba.gif',save_all = True, append_images=sequence[1:])

将多张静态图片生成 gif 的代码,这个年底可以将每年的图片合并成一个大的 gif 以留作回忆,倒是很有用的

  1. # coding=utf8
  2. import imageio
  3. import os
  4. path = '../images'
  5. filenames = []
  6. for files in os.listdir(path):
  7. if files.endswith('jpg') or files.endswith('jpeg') or files.endswith('png'):
  8. file = os.path.join(path,files)
  9. filenames.append(file)
  10. images = []
  11. for filename in filenames:
  12. images.append(imageio.imread(filename))
  13. imageio.mimsave('movie.gif', images, duration = 0.3)

原作者不建议使用 image2gif 包,详见一楼回答

当然如果你有需求将一组尺寸一样的照片生成 gif,可以邮箱 hexiaodong1992@outlook.com

参考链接:

  1. 知乎 CVPy 专栏
  2. imageio 官方文档

最后恰饭 阿里云全系列产品/短信包特惠购买 中小企业上云最佳选择 阿里云内部优惠券