Home > Blockchain >  How to generate a GIF without saving/importing image files?
How to generate a GIF without saving/importing image files?

Time:06-21

Say I use the following method to create a three images. I then want to combine these three images into a GIF & display the GIF (jupyter notebook, python 3). All the methods I've seen online & stackoverflow for creating GIFs include saving the images as files & then importing them. For instance, this thread. But is there a way to just generate a gif without having to save/import image files? So, in the following code, using three versions of the im=Image.fromarray(arr.astype('uint8')) generated image to create a gif on the spot?

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()

CodePudding user response:

I guess you need something like this. GIF is an image file type so you have to save it to have one.

#! /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()

Then open im.gif with a browser or some app that can show animated GIFs.

If you really don't want to save the GIF but just show it, you can do something like this

#! /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())
  • Related