首页 > 解决方案 > 如何使用 Pillow 将动画 GIF 保存到变量中

问题描述

我从这里发现我可以使用 Pillow 创建和保存动画 GIF。但是,该save方法似乎没有返回任何值。

我可以将 GIF 保存到文件中,然后使用 打开该文件Image.open,但这似乎没有必要,因为我真的不希望保存 GIF。

如何将 GIF 保存到变量而不是文件?也就是说,我希望能够some_variable.show()制作和显示 GIF,而不必将 GIF 保存到我的计算机上。

标签: variablessavegifpillow

解决方案


为避免写入任何文件,您只需将图像保存到BytesIO对象即可。例如:

#!/usr/bin/env python

from __future__ import division
from PIL import Image
from PIL import ImageDraw
from io import BytesIO

N = 25          # number of frames

# Create individual frames
frames = []
for n in range(N):
    frame = Image.new("RGB", (200, 150), (25, 25, 255*(N-n)//N))
    draw = ImageDraw.Draw(frame)
    x, y = frame.size[0]*n/N, frame.size[1]*n/N
    draw.ellipse((x, y, x+40, y+40), 'yellow')
    # Saving/opening is needed for better compression and quality
    fobj = BytesIO()
    frame.save(fobj, 'GIF')
    frame = Image.open(fobj)
    frames.append(frame)

# Save the frames as animated GIF to BytesIO
animated_gif = BytesIO()
frames[0].save(animated_gif,
               format='GIF',
               save_all=True,
               append_images=frames[1:],      # Pillow >= 3.4.0
               delay=0.1,
               loop=0)
animated_gif.seek(0,2)
print ('GIF image size = ', animated_gif.tell())

# Optional: display image
#animated_gif.seek(0)
#ani = Image.open(animated_gif)
#ani.show()

# Optional: write contents to file
animated_gif.seek(0)
open('animated.gif', 'wb').write(animated_gif.read())

最后,变量animated_gif包含下图的内容:

日落

但是,在 Python 中显示动画 GIF 并不是很可靠。ani.show()从上面的代码中只显示我机器上的第一帧。


推荐阅读