4
4
from django.core.files.uploadedfile import SimpleUploadedFile
6
7
class ExtendedImageField(models.ImageField):
8
Extended ImageField that can resize image before saving it.
8
"""Extended ImageField that can resize image before saving it."""
10
10
def __init__(self, *args, **kwargs):
11
11
self.width = kwargs.pop('width', None)
12
12
self.height = kwargs.pop('height', None)
13
13
super(ExtendedImageField, self).__init__(*args, **kwargs)
16
15
def save_form_data(self, instance, data):
17
16
if data is not None and data != self.default:
19
18
data = self.default
20
19
if instance.avatar != self.default:
21
instance.avatar.delete()
20
instance.avatar.delete()
23
22
if hasattr(data, 'read') and self.width and self.height:
24
content = self.resize_image(data.read(), width=self.width, height=self.height)
25
data = SimpleUploadedFile(instance.user.username + ".png", content, "image/png")
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')
26
27
super(ExtendedImageField, self).save_form_data(instance, data)
29
29
def resize_image(self, rawdata, width, height):
31
Resize image to fit it into (width, height) box.
30
"""Resize image to fit it into (width, height) box."""
33
31
from PIL import Image
35
33
image = Image.open(StringIO(rawdata))