PotatoBox
PotatoBox

Reputation: 608

Django: Resize image on pre-save signal

I have a model that contains ImageField field and I want to resize provided image if it's dimensions are too big (over 600x600). My signal looks like this:

from django.conf import settings
from django.db.models.signals import pre_save
from PIL import Image

def resize_profile_picture(sender, instance, **kwargs):
    img = Image.open(instance.profile_picture)
    print(img.__dict__['_size'])
    if any([img.width > settings.MAX_PROFILE_PICTURE_WIDTH, img.height > settings.MAX_PROFILE_PICTURE_HEIGHT]):
        img.thumbnail(settings.MAX_PROFILE_PICTURE_DIMENSIONS)
        print(img.__dict__['_size'])

pre_save.connect(resize_profile_picture, sender=get_user_model())

Those prints shows that in fact the image is being resized, from (645, 374) to (600, 347), but the problem is that this thumbnail is not being saved and I still have picture in the original size. Since thumbnail operates on the same picture it is invoked on, I can't find any reason why it does not work, because according to the documentation, thumbnail returns NoneType so in my understanding it's not up to me to save modified picture or return it (But I tried nonetheless, no luck).

Upvotes: 2

Views: 781

Answers (1)

Daniele Bernardini
Daniele Bernardini

Reputation: 1536

You need to save the img and reassign it to instance.profile_picture like this:

from django.conf import settings
from django.db.models.signals import pre_save
from PIL import Image

def resize_profile_picture(sender, instance, **kwargs):
    img = Image.open(instance.profile_picture)
    print(img.__dict__['_size'])
    if any([img.width > settings.MAX_PROFILE_PICTURE_WIDTH, img.height > settings.MAX_PROFILE_PICTURE_HEIGHT]):
        img.thumbnail(settings.MAX_PROFILE_PICTURE_DIMENSIONS)
        img.save("thumbnail.png")
        instance.profile_picture = open("thumbnail.png")
        print(img.__dict__['_size'])

pre_save.connect(resize_profile_picture, sender=get_user_model())

Upvotes: 3

Related Questions