Login

Resize or Modify an image before saving

Author:
asura
Posted:
December 29, 2016
Language:
Python
Version:
1.10
Score:
1 (after 1 ratings)

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

  1. Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 2 months, 2 weeks ago
  2. Python Django CRUD Example Tutorial by tuts_station 3 months ago
  3. Browser-native date input field by kytta 4 months, 2 weeks ago
  4. Generate and render HTML Table by LLyaudet 4 months, 4 weeks ago
  5. My firs Snippets by GutemaG 5 months ago

Comments

Nikita-L (on July 8, 2017):

Got an AttributeError, so changed "im = im.resize( (100,100) )" just to "im.resize( (100,100) )" Thank you for the snippet!

#

GeoffMahugu (on January 26, 2018):

Thanks for the snippet

#

pgdju (on March 30, 2018):

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?

#

FredTingey (on April 7, 2020):

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

def save(self, *args, **kwargs):
    # Opening the uploaded image
    img = Image.open(self.image)

    if img.height > 200 or img.width > 200:

        output_size = (200, 200)
        img.thumbnail(output_size)
        img = img.convert('RGB')

        output = BytesIO()
        img.save(output, format='JPEG')
        output.seek(0)

        # change the imagefield value to be the newley modifed image value
        self.image = InMemoryUploadedFile(output, 'ImageField',
                                          f'{self.image.name.split(".")[0]}.jpg',
                                          'image/jpeg', sys.getsizeof(output),
                                          None)

    super().save(*args, **kwargs)

#

fincan (on February 22, 2022):

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?

#

fincan (on February 23, 2022):

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.