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

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!

#

Please login first before commenting.