atropa belladona
atropa belladona

Reputation: 524

How to plug a function inside ImageField

I'm trying to upload images from Django admin. the files are bigger most of them more than 5 MB, I want to rescale them so the size should be less than 1 MB before upload.

I have a function that could re-scale the image and is working fine, But I'm not sure how to plug that function into ImageField in Django models.

def scaled_image(input_image_path, output_image_path, width=600, height=None):
    image = Image.open(input_image_path)
    w, h = image.size
    if width and height:
        max_size = (width, height)
    elif width:
        max_size = (width, h)
    elif height:
        max_size = (w, height)
    else:
        # No width or height specified
        sys.exit("Width or height required!")
    image.thumbnail(max_size, Image.ANTIALIAS)
    image.save(output_image_path)
    scaled_image = Image.open(output_image_path)
    return scaled_image

Now how can I change my ImageField so that should work

doucment_image = models.ImageField(upload_to='sellerinfo', null=True, blank=True)

Help would be appreciated. Thanks

Upvotes: 0

Views: 33

Answers (1)

Benbb96
Benbb96

Reputation: 2283

You could try to override the save function of your Model :

class Model(models.Model):
    doucment_image = models.ImageField(upload_to='sellerinfo', null=True, blank=True)

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        # Call scaled_image if doucment_image is provided
        if self.doucment_image:
            self.doucment_image = scaled_image(self.doucment_image.path, self.doucment_image.path)

Upvotes: 1

Related Questions