Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

I am trying to implement a Django ImageField class function for resizing images however I am not certain where this function accepts my new image dimensions

Running on Linux and Python 3.7

I've had a look at this documentation, but can't quite make sense of it: https://docs.djangoproject.com/en/1.11/_modules/django/db/models/fields/files/#ImageField

I'd really appreciate it if someone can show me an example of how to use this function.

EDIT

I haven't successfully managed to resize my image dimensions yet, which is what i am trying to achieve. How may I resize this image before I save it given it is being fetched by ImageField (I found the update_dimensions_fields class function for ImageField however i cant figure out how to use it)

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 = models.ImageField(upload_to=get_image_path, blank=True, null=True)

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        # I would like to use the function beneath to resize my images before I save them to my database
        self.post_image.update_dimension_fields(self, instance, force=False, *args, **kwargs)

        super().save(*args, **kwargs) # Call the "real" save() method.

    class Meta:
        verbose_name_plural = "Posts"

like image 484
rymanso Avatar asked Jul 19 '19 11:07

rymanso


People also ask

How do I resize and save an image in Python?

Practical Data Science using Python The Image module from pillow library has an attribute size. This tuple consists of width and height of the image as its elements. To resize an image, you call the resize() method of pillow's image class by giving width and height.

How do you change the size of an image in Python?

To resize an image, you call the resize() method on it, passing in a two-integer tuple argument representing the width and height of the resized image. The function doesn't modify the used image; it instead returns another Image with the new dimensions.


2 Answers

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
like image 136
Stevy Avatar answered Sep 27 '22 21:09

Stevy


**

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"
like image 30
dennisiluma Avatar answered Sep 27 '22 22:09

dennisiluma