About Generating Animated GIFs on the Fly

You can generate animated GIFs on the fly using the Pillow library, as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from io import BytesIO
from random import randrange
from PIL import Image, ImageDraw
from django.http import HttpResponse

def create_gif(request):
    frames = []
    outer_radius = 25
    inner_radius = 15
    for i in range(10):
        image = Image.new("RGB", (100, 100), color="white")
        draw = ImageDraw.Draw(image)
        center_x = randrange(40, 60)
        center_y = randrange(40, 60)
        draw.ellipse(
            (
                center_x - outer_radius,
                center_y - outer_radius,
                center_x + outer_radius,
                center_y + outer_radius,
            ),
            fill="#215a00",
        )
        draw.ellipse(
            (
                center_x - inner_radius,
                center_y - inner_radius,
                center_x + inner_radius,
                center_y + inner_radius,
            ),
            fill="#fff",
        )
        frames.append(image)
    # Create an in-memory buffer to hold the GIF data
    buffer = BytesIO()
    frames[0].save(
        buffer,
        format="gif",
        save_all=True,
        append_images=frames[1:],
        loop=0,
        duration=400,  # ms
    )
    gif_data = buffer.getvalue()
    buffer.close()
    # Return the GIF data as an HTTP response
    return HttpResponse(gif_data, content_type="image/gif")

Tips and Tricks Programming Django 4.2 Django 3.2 Django 2.2 Python 3 Pillow GIF