1from django.db import models
2from my.images import make_thumbnail
3
4
5class Image(models.Model):
6 image = models.ImageField(upload_to='')
7 thumbnail = models.ImageField(upload_to='', editable=False)
8 icon = models.ImageField(upload_to='', editable=False)
9
10 def save(self, *args, **kwargs):
11 # save for image
12 super(Image, self).save(*args, **kwargs)
13
14 make_thumbnail(self.thumbnail, self.image, (200, 200), 'thumb')
15 make_thumbnail(self.icon, self.image, (100, 100), 'icon')
16
17 # save for thumbnail and icon
18 super(Image, self).save(*args, **kwargs)
19
1from django.core.files.base import ContentFile
2import os.path
3from PIL import Image
4from io import BytesIO
5
6
7def make_thumbnail(dst_image_field, src_image_field, size, name_suffix, sep='_'):
8 """
9 make thumbnail image and field from source image field
10
11 @example
12 thumbnail(self.thumbnail, self.image, (200, 200), 'thumb')
13 """
14 # create thumbnail image
15 image = Image.open(src_image_field)
16 image.thumbnail(size, Image.ANTIALIAS)
17
18 # build file name for dst
19 dst_path, dst_ext = os.path.splitext(src_image_field.name)
20 dst_ext = dst_ext.lower()
21 dst_fname = dst_path + sep + name_suffix + dst_ext
22
23 # check extension
24 if dst_ext in ['.jpg', '.jpeg']:
25 filetype = 'JPEG'
26 elif dst_ext == '.gif':
27 filetype = 'GIF'
28 elif dst_ext == '.png':
29 filetype = 'PNG'
30 else:
31 raise RuntimeError('unrecognized file type of "%s"' % dst_ext)
32
33 # Save thumbnail to in-memory file as StringIO
34 dst_bytes = BytesIO()
35 image.save(dst_bytes, filetype)
36 dst_bytes.seek(0)
37
38 # set save=False, otherwise it will run in an infinite loop
39 dst_image_field.save(dst_fname, ContentFile(dst_bytes.read()), save=False)
40 dst_bytes.close()
41