Small snippet that will resize all images before they uploaded to the server.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | from django.db import models
from PIL import Image
from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile
import sys
# Create your models here.
class Modify(models.Model):
img = models.ImageField()
def save(self):
#Opening the uploaded image
im = Image.open(self.img)
output = BytesIO()
#Resize/modify the image
im = im.resize( (100,100) )
#after modifications, save it to the output
im.save(output, format='JPEG', quality=100)
output.seek(0)
#change the imagefield value to be the newley modifed image value
self.img = InMemoryUploadedFile(output,'ImageField', "%s.jpg" %self.img.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None)
super(Modify,self).save()
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Got an AttributeError, so changed "im = im.resize( (100,100) )" just to "im.resize( (100,100) )" Thank you for the snippet!
#
Thanks for the snippet
#
Thanks for this snippet. Unfortunately, in my save function, I would like to change the filename of the file image just before "super(Modify,self).save()" but Django create another image with extra characters, something like "2018-03-23_optic.png" becomes "2018-03-23_optic_JJOPPPX.png". How can I keep my own filename?
#
thank you very much for this; it helped me a lot! I had to make a couple of minor changes
a) to convert the images to jpeg prior to saving them b) only apply the resize if the image is too big c) use thumbnail() to do the resize
#
I tried your snippet but there is a problem that I could not solve. If thumbnailed a portrait oorientated photo, the photo is rotated as landscape. How can I prevent rotation?
#
I solved the issue with Pil.ImageOps.exif_transpose
``` ...
image.thumbnail((780, 780)) image = ImageOps.exif_transpose(image) image.save(output, format='JPEG', quality=100) ... ```
#
Please login first before commenting.