如何生成GIF而不保存/导入图像文件?



假设我使用以下方法创建三个图像。然后我想把这三张图片组合成一张GIF;显示GIF (jupyter notebook, python 3)。我在网上看到的所有方法&用于创建gif的stackoverflow包括将图像保存为文件&然后再进口。例如,这个线程。但是有没有一种方法可以生成gif而不必保存/导入图像文件?那么,在下面的代码中,使用三个版本的im=Image.fromarray(arr.astype('uint8'))生成的图像在现场创建一个gif呢?

import numpy as np
from PIL import Image
arr = np.random.randint(low = 0, high = 255, size = (300, 300, 3))
im = Image.fromarray(arr.astype('uint8'))
im.show()

我想你需要这样的东西。GIF是一种图像文件类型,所以你必须保存它。

#! /usr/bin/env python3
import numpy as np
from PIL import Image

im = []
for n in range(20):
arr = np.random.randint(low = 0, high = 255, size = (300, 300, 3))
im.append(Image.fromarray(arr.astype('uint8')))
im[0].save('im.gif', save_all=True, append_images=im[1:], optimize=False, duration=200, loop=0)
#im[0].show()

然后用浏览器或一些可以显示动画gif的应用程序打开im.gif

如果你真的不想保存GIF而只想显示它,你可以这样做

#! /usr/bin/env python3
import base64
import io
import numpy as np
from PIL import Image
from viaduc import Viaduc

im = []
for n in range(20):
arr = np.random.randint(low = 0, high = 255, size = (300, 300, 3))
im.append(Image.fromarray(arr.astype('uint8')))

buffer = io.BytesIO()
im[0].save(buffer, format='GIF', save_all=True, append_images=im[1:], optimize=False, duration=200, loop=0)
buffer.seek(0)
data_uri = base64.b64encode(buffer.read()).decode('ascii')

class Presentation(Viaduc.Presentation):
width = 300
height = 300
title = 'gif'
html = '''
<!DOCTYPE html>
<head>
{{bootstrap_meta}} {{bootstrap_css}}
<title>{{title}}</title>
</head>
<body>
<img src="data:image/gif;base64,''' + data_uri + '''">
{{bootstrap_js}}
</body>  
</html>
'''

if __name__ == '__main__':
Viaduc(presentation=Presentation())

最新更新