1
from StringIO import StringIO
2
from django.db import models
4
from django.core.files.uploadedfile import SimpleUploadedFile
7
class ExtendedImageField(models.ImageField):
8
"""Extended ImageField that can resize image before saving it."""
10
def __init__(self, *args, **kwargs):
11
self.width = kwargs.pop('width', None)
12
self.height = kwargs.pop('height', None)
13
super(ExtendedImageField, self).__init__(*args, **kwargs)
15
def save_form_data(self, instance, data):
16
if data is not None and data != self.default:
19
if instance.avatar != self.default:
20
instance.avatar.delete()
22
if hasattr(data, 'read') and self.width and self.height:
23
content = self.resize_image(
24
data.read(), width=self.width, height=self.height)
25
data = SimpleUploadedFile(
26
instance.user.username + '.png', content, 'image/png')
27
super(ExtendedImageField, self).save_form_data(instance, data)
29
def resize_image(self, rawdata, width, height):
30
"""Resize image to fit it into (width, height) box."""
33
image = Image.open(StringIO(rawdata))
35
oldw, oldh = image.size
37
if oldw > width or oldh > height:
39
x = int(round((oldw - oldh) / 2.0))
40
image = image.crop((x, 0, (x + oldh) - 1, oldh - 1))
42
y = int(round((oldh - oldw) / 2.0))
43
image = image.crop((0, y, oldw - 1, (y + oldw) - 1))
44
image = image.resize((width, height), resample=Image.ANTIALIAS)
45
except Exception, err:
50
image.save(string, format='PNG')
51
return string.getvalue()