About Generating Animated GIFs on the Fly

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

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