django model with photo resize

 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
29
30
31
32
33
34
35
36
37
38
39
class Picture(models.Model):
description = models.TextField()
big_picture = models.ImageField(upload_to="big_picture/%Y/%m/%d/", max_length=100)
middle_picture = models.ImageField(upload_to="middle_picture/%Y/%m/%d", blank=True, editable=False, max_length=100)
small_picture = models.ImageField(upload_to="small_picture/%Y/%m/%d", blank=True, editable=False, max_length=100)
def create_middle(self, path):
im = PIL.Image.open(path)
format = im.format
size = (200, 200)
im.thumbnail(size, PIL.Image.ANTIALIAS)
return im.tostring(format.lower(), 'RGB')
def create_small(self, path):
im = PIL.Image.open(path)
format = im.format
x,y = im.size
min_size = min(x, y)
region = im.crop((0, 0, min_size, min_size))
size = (100, 100)
region.thumbnail(size, PIL.Image.ANTIALIAS)
return region.tostring(format.lower(), 'RGB')
def save(self):
if self.big_picture:
image_path = self.get_big_picture_filename()
self.save_middle_picture_file(image_path, self.create_middle(image_path), save=False)
self.save_small_picture_file(image_path, self.create_small(image_path), save=False)
super(Picture, self).save()
class Admin:
pass
class Meta:
verbose_name = "Picture"
verbose_name_plural = "Pictures"
def __unicode__(self):
return self.description