django

Creating thumbnail in Django with using django-imagekit

Django-imagekit is an app for processing images. You can programmatically change images with imagekit. For this blog post, we will create thumbnails and look for its Django Rest Framework usage (DRF).

1. Installation of django-imagekit

pip install pillow
pip install django-imagekit

INSTALLED_APPS = [
'imagekit',
]

2. Creating thumbnail with django-imagekit

For creating a thumbnail in Django from an image we will use ImageSpecField. An image spec is a type of image generator that generates a new image from a source image. Now let’s look for a specific example.

Models.py

class Category(models.Model):
    name = models.CharField(
        verbose_name=_("Category Name"),
        help_text=_("Required and unique"),
        max_length=255,
        unique=True,
    )
    picture = models.ImageField(null=True, upload_to="images/", blank=True, verbose_name="Category picture")

    thumbnail150x150 = ImageSpecField(source='picture', processors=[ResizeToFill(150, 150)], format="PNG",
                                      options={'quality': 60})
    cdate = models.DateTimeField(auto_now_add=True)
    udate = models.DateTimeField(auto_now=True)

In the above example, we specified source=’picture’, in this way we tell that use picture field as a source and generate a new image.

So in your templates you can simply use it like below:

<img src="{{ category.thumbnail150x150.url }}" alt="img">

 

If you want to not create a new image, just change the original image, then we will use ProcessedImageField and we replace a source to upload_to.

class Category(models.Model):
    name = models.CharField(
        verbose_name=_("Category Name"),
        help_text=_("Required and unique"),
        max_length=255,
        unique=True,
    )
    thumbnail150x150 = ProcessedImageField(upload_to="images/", processors=[ResizeToFill(150, 150)], format="PNG",
                                      options={'quality': 60})
    cdate = models.DateTimeField(auto_now_add=True)
    udate = models.DateTimeField(auto_now=True)

3. django-imagekit usage with DRF(Django Rest Framework)

Serializers use the local_fields. So we will handle it in our serializers.py

class CategorySerializer(serializers.ModelSerializer):
    picture = serializers.SerializerMethodField()
    thumbnail = serializers.SerializerMethodField()

    class Meta:
        model = Category
        fields = ('id', 'name', 'picture','thumbnail')

    def get_picture(self, obj):
        return obj.picture.url

    def get_thumbnail(self, obj):
        return obj.thumbnail150x150.url

 

 

Tagged , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *