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"
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.
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.
You could use the django-resized library. It resizes images when uploaded and stores them for you.
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
**
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With