تغيير اللغه الي العربية

My Blog


All posts

Reduce Image Size Before Uploading


When we created custom user model we added image field to the user, but what if that user added an image like 100mb or more... we don't want that.

so let's fix it.

- we will use Pillow so make sure it installed, and BTW its required to have Pillow if you will use the ImageField in Django.

$ pip install Pillow

- In the models.py we will edit the save function using Pillow to reduce the image resolution.

# models.py
from PIL import Image

class CustomUser(AbstractUser):
....
....
....
def save(self, *args, **kwargs):
super(CustomUser, self).save()
"""reduce image size before upload to server"""
if self.image:
basewidth = 350
img = Image.open(self.image)
wpercent = (basewidth / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
img = img.resize((basewidth, hsize), Image.ANTIALIAS)
img.save(self.image.path)


- lets explain this code

first we declared a basewidth, which is the maximum width of the image that will be allowed.

Then we opened the image to start editing it using Image.open().

And then we will calculate the new height of the image based on the ratio of the new width to the original width.


The ANTIALIAS option is used to ensure that the image is resized with high quality.


And that's it! You can increase the basewidth if you want to make the image bigger, for example you can use 1024 if it will be a cover image for the website header.

I hope the tutorial was simple.
Feel free to reach out if you have any questions.

Join to discord Server Here - Django Learn Together.



Last Updated: 1 month, 1 week ago
Views: 377