How to resize an ImageField image before saving it in python Django model

**

This will work **First of all install "PIL Fork" using 'pip install pillow

from PIL import Image


def __str__(self):
    return self.title


def save(self, *args, **kwargs):
    super(Posts, self).save(*args, **kwargs)
    imag = Image.open(self.post_image.path)
    if imag.width > 400 or imag.height> 300:
        output_size = (400, 300)
        imag.thumbnail(output_size)
        imag.save(self.post_image.path)
class Meta:
    verbose_name_plural = "Posts"

You could use the django-resized library. It resizes images when uploaded and stores them for you.

Usage

from django_resized import ResizedImageField

class Posts(models.Model):
    title = models.CharField(max_length=200, blank=True)
    body = models.TextField(blank=True)
    created_at = models.DateTimeField(default=datetime.datetime.now)
    post_image = ResizedImageField(size=[500, 300], upload_to=get_image_path, blank=True, null=True)

    def __str__(self):
        return self.title

Options

  • size - max width and height, for example [640, 480]
  • crop - resize and crop. ['top', 'left'] - top left corner, ['middle', - 'center'] is center cropping, ['bottom', 'right'] - crop right bottom corner.
  • quality - quality of resized image 1..100
  • keep_meta - keep EXIF and other meta data, default True
  • force_format - force the format of the resized image, available formats are the one supported by pillow, default to None

Tags:

Python

Django