Answer a question

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"

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
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐