Django : resize an image on upload

This is a typical use-case : your site/app allows users to upload a picture. But you don’t want to store full size 8Mb picture, and still, it’s comfortable for the user to not have to manually resize the image before uploading it. The solution : resizing the image “on the fly” when receiving it on the server side.

Another use-case, also quite common : you need to generate a thumbnail for the uploaded picture. The following code will help you too.

This script is re-sizing the image only if it’s a new PicturePost (we check that the object key isn’t set).

We’re doing some calculation to get the right ratio before re-sizing the image. We can’t use the thumbnail() method because we want to resize based only on the width of the image. The thumbnail() method will resize the image based on the biggest between width and height.

We convert the image to jpeg with a 90 quality (the default is 75, 100 meaning no jpeg compression at all).

We also keep the exif information if its exists. By default, it’ll disappear, so we have to manually add them again when saving the resized file.

Once it’s resized, we save the object into the database.

You can also use the same logic to create a thumbnail of the image and store it into another ImageField field. 😉

Published by

Louwii

Web developer, geek, car enthusiast, photographer, DIYer, video gamer... I like many things, maybe too many?

One thought on “Django : resize an image on upload”

  1. it looks pretty good, but can u explane from where did u get
    “super(CarPost,” ?
    ur model is PicturePost and i cant see any PicturePost imports.

    and how to combine ur code with :
    class Profile(models.Model):
    user = foreignkey to User model.
    avatar = imagefield…. blabbla.

    ProfileUpdateView(UpdateView):
    ……….
    ………

Leave a Reply to konopli Cancel reply

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