如何使用 Pillow 将动画 GIF 保存到变量

How to save an animated GIF to a variable using Pillow

我从 here that I can create and save animated GIFs using Pillow. However, it doesn't look like the save method returns 中找到任何值。

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

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

为避免写入任何文件,您可以将图像保存到 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() 上面的代码在我的机器上只显示第一帧。