About ImageKit Image Generation

The django-imagekit package allows flexible image version creation in templates or APIs. Here's how to create a thumbnail version of an image in an ImageField:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from django.core.files.storage import default_storage as storage
from imagekit.cachefiles import ImageCacheFile
from .models import Post
from .imagegenerators import Thumbnail100x100

post = Post.objects.first()
post_thumbnail_url = None
if post and storage.exists(post.cover_image.name):
    try:
        source_file = storage.open(post.cover_image.name, "rb")
        image_generator = Thumbnail100x100(source=source_file)
        result = ImageCacheFile(image_generator)
        post_thumbnail_url = result.url
    except FileNotFoundError:
        pass

The Thumbnail100x100 generator class can be defined as follows:

1
2
3
4
5
6
7
8
9
from imagekit import ImageSpec, register
from imagekit.processors import ResizeToFill

class Thumbnail100x100(ImageSpec):
    processors = [ResizeToFill(100, 100)]
    format = "JPEG"
    options = {"quality": 90}

register.generator("media_management:thumbnail100x100", Thumbnail100x100)

Tips and Tricks Programming Development Django 4.2 Django 3.2 Django 2.2 Pillow django-imagekit