variables - 如何使用 Pillow 将动画 GIF 保存到变量中
问题描述
我从这里发现我可以使用 Pillow 创建和保存动画 GIF。但是,该save
方法似乎没有返回任何值。
我可以将 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()
从上面的代码中只显示我机器上的第一帧。
推荐阅读
- firebase - 了解 index.js firebase 函数中的部署目标
- xml - 字符串连接functoid不将映射值返回到目标记录
- ios - 在 ios 中从不同的视图控制器(不是同时)多次调用相同的 Web 服务
- python - 将值应用于列并按这些值对所有列进行分组
- python - 需要帮助:Python 文件路径
- java - 带有 Picocli 的 CLI:在调用子命令之前调用主命令
- python - 将网页中的抓取标题写入熊猫框架
- php - 如何将 textarea 值作为单独的变量获取?
- android - 忽略起始空格和特殊字符仅大写字符串中的第一个字母
- c++ - 选择的回溯值