Django image resizing and convert before upload
First, it's best to establish the correct language. Django and Python exist only on the server side. Therefore, anything they manipulate, save, or otherwise use, has to be first sent to the server. If Django or Python is to manage the photo, the user MUST upload this photo to the server first. Once the photo is uploaded, Django is free to make changes before storing the file.
If your concern is with upload bandwidth, and you don't want large files being uploaded, you will have to resize and reformat the photo on the client side. If this is a web application, this can be done using Javascript, but can not be done with Python, since Python does not operate on the client side for an application like yours.
If your concern is not with bandwidth, then you're free to have the user "upload" the file, but then have Django resize and reformat it before saving.
You are correct that you will want to override your save function for the photo object. I would recommend using a library to handle the resizing and reformatting, such as sorl.
from sorl.thumbnail import ImageField, get_thumbnail
class MyPhoto(models.Model):
image = ImageField()
def save(self, *args, **kwargs):
if self.image:
self.image = get_thumbnail(self.image, '500x600', quality=99, format='JPEG')
super(MyPhoto, self).save(*args, **kwargs)
Sorl is just a library I am confident and familiar with, but it takes some tuning and configuration. You can check out Pillow or something instead, and just replace the line overriding self.image
.
I also found a similar question here.
Edit: saw the update to your comment response above. Also note that if your webserver is handling Django, and your files are being saved to some CDN, this method will work. The image will be resized on the webserver before being uploaded to your CDN (assuming your configuration is as I'm assuming).
Hope this helps!
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
class profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.CharField(max_length=300)
location = models.CharField(max_length=99)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
def save(self):
super().save() # saving image first
img = Image.open(self.image.path) # Open image using self
if img.height > 300 or img.width > 300:
new_img = (300, 300)
img.thumbnail(new_img)
img.save(self.image.path) # saving image at the same path
This example shows how to upload image after image re-sizing. Change the pixel of new_img, whatever you want.