About Generating Favicons on the Fly

Create favicons dynamically 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
48
49
from io import BytesIO
from PIL import Image, ImageDraw
from django.http import HttpResponse

def create_favicon(request):
    # Create a blank image with an alpha channel
    image = Image.new("RGBA", (100, 100), (255, 255, 255, 0))

    outer_radius = 25
    inner_radius = 15
    center_x = 50
    center_y = 50
    draw = ImageDraw.Draw(image)
    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",
    )

    # Generate the different sizes of the favicon
    sizes = [(16, 16), (32, 32), (48, 48)]
    images = []
    for size in sizes:
        image_version = image.resize(size, resample=Image.BICUBIC)
        images.append(image_version)

    # Create a BytesIO object to hold the ICO file
    buffer = BytesIO()
    images[0].save(buffer, "ICO", sizes=[(s[0], s[1]) for s in sizes])
    buffer.seek(0)

    # Create an HttpResponse object with the ICO file
    response = HttpResponse(buffer.read(), content_type="image/x-icon")
    response["Content-Disposition"] = "inline; filename=favicon.ico"

    return response

Then you can set the favicon for your website with this URL rule:

1
2
3
4
5
6
from django.urls import path
from favicon.views import favicon_view

urlpatterns = [
    path("favicon.ico", create_favicon, name="favicon"),
]

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