Django Image Resizing And Convert Before Upload
Solution 1:
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
classMyPhoto(models.Model):
image = ImageField()
defsave(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!
Solution 2:
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
classprofile(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')
defsave(self):
super().save() # saving image first
img = Image.open(self.image.path) # Open image using selfif img.height > 300or 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.
Solution 3:
Here is an app that can take care of that: django-smartfields. It will also remove an old image whenever a new one is uploaded.
from django.db import models
from smartfields import fields
from smartfields.dependencies import FileDependency
from smartfields.processors import ImageProcessor
classImageModel(models.Model):
image = fields.ImageField(dependencies=[
FileDependency(processor=ImageProcessor(
format='JPEG', scale={'max_width': 300, 'max_height': 300}))
])
Solution 4:
EDIT4 : full working code can be found here (the code below still has some mistakes)
Still fighting, but there is progress ^^ : I am trying to do the resizing and convertion in memory with PIL (and seeing the amount of questions on the subject, it seems that I am not the only one ^^). My code so far (in Models.py):
from PIL import Image as Img
import StringIO
from django.core.files import File
classMymodel(models.Model):
#blablabla
photo = models.ImageField(uppload_to="...", blank=True)
defsave(self, *args, **kwargs):
if self.photo:
image = Img.open(StringIO.StringIO(self.photo.read()))
image.thumbnail((100,100), Img.ANTIALIAS)
output = StringIO.StringIO()
image.save(output, format='JPEG', quality=75)
output.seek(0)
self.photo = File(output, self.photo.name())
super(Mymodel, self).save(*args, **kwargs)
I have an error at "photo = File(output, photo.name())"
Thanks
EDIT : Sorry, it was a simple mistake (forgot the self.) corrected in code. Now I have the error "TypeError, 'unicode' object is not callable", at the same line.
EDIT2: Saw something about "output.getvalue()" here but don't really know if could be of any help.
EDIT3 : Solved!! Code below.
from PIL import Image as Img
import StringIO
from django.core.files.uploadedfile import InMemoryUploadedFile
classMymodel(models.Model):
photo = models.ImageField(upload_to="...", blank=True)
defsave(self, *args, **kwargs):
if self.photo:
image = Img.open(StringIO.StringIO(self.photo.read()))
image.thumbnail((200,200), Img.ANTIALIAS)
output = StringIO.StringIO()
image.save(output, format='JPEG', quality=75)
output.seek(0)
self.photo= InMemoryUploadedFile(output,'ImageField', "%s.jpg" %self.photo.name, 'image/jpeg', output.len, None)
super(Mymodel, self).save(*args, **kwargs)
Solution 5:
Here is one more package that works for me with minimal code modification - django-resized.
models.py
from django_resized import ResizedImageField
classPost(models.Model):
image = ResizedImageField(upload_to='uploads/%Y/%m/%d')
settings.py
DJANGORESIZED_DEFAULT_SIZE = [1024, 768]
DJANGORESIZED_DEFAULT_QUALITY = 75DJANGORESIZED_DEFAULT_KEEP_META = TrueDJANGORESIZED_DEFAULT_FORCE_FORMAT = 'JPEG'DJANGORESIZED_DEFAULT_FORMAT_EXTENSIONS = {'JPEG': ".jpg"}
DJANGORESIZED_DEFAULT_NORMALIZE_ROTATION = True
That's it!
Post a Comment for "Django Image Resizing And Convert Before Upload"