Login

Resize or Modify an image before saving

Author:
asura
Posted:
December 29, 2016
Language:
Python
Version:
1.10
Tags:
image pil resize save imagefield modified pre_save override
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. Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 5 months ago
  2. Crispy Form by sourabhsinha396 6 months ago
  3. ReadOnlySelect by mkoistinen 6 months, 1 week ago
  4. Verify events sent to your webhook endpoints by santos22 7 months, 1 week ago
  5. Django Language Middleware by agusmakmun 7 months, 2 weeks 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)

#

Please login first before commenting.