-# initiated from http://djangosnippets.org/snippets/2145/
-
-import os
-import re
-from PIL import Image
-
-from django.conf import settings
-
-from django.db.models.signals import post_save, pre_delete
-from django.template import Library
-
-register = Library()
-
-def thumbnail(image, size='100x100'):
- # defining the size
- x, y = [int(x) for x in size.split('x')]
- # defining the filename and the miniature filename
- try:
- filehead, filetail = os.path.split(image.path)
- except (AttributeError, ValueError):
- # return transparent pixel if the image doesn't actually exist
- return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII='
- basename, format = os.path.splitext(filetail)
- if format.lower() not in ('.jpg', '.jpeg'):
- format = '.png'
- miniature = basename + '__' + size + format
- filename = image.path
- miniature_filename = os.path.join(filehead, miniature)
- filehead, filetail = os.path.split(image.url)
- miniature_url = filehead + '/' + miniature
- if os.path.exists(miniature_filename) and \
- os.path.getmtime(filename) > os.path.getmtime(miniature_filename):
- os.unlink(miniature_filename)
- # if the image wasn't already resized, resize it
- if not os.path.exists(miniature_filename) and os.path.exists(filename):
- image = Image.open(filename)
- if abs( (1.0*x/y) - (1.0*image.size[0]/image.size[1]) ) > 0.1:
- # aspect ratio change, crop the image first
- box = [0, 0, image.size[0], int(image.size[0] * (1.0*y/x))]
-
- if box[2] > image.size[0]:
- box = [int(t*(1.0*image.size[0]/box[2])) for t in box]
- if box[3] > image.size[1]:
- box = [int(t*(1.0*image.size[1]/box[3])) for t in box]
-
- if image.size[0] > image.size[1]: # landscape
- box[0] = (image.size[0] - box[2]) / 2 # keep the middle
- box[2] += box[0]
- else:
- box[1] = (image.size[1] - box[3]) / 4 # keep mostly the top
- box[3] += box[1]
-
- image = image.crop(box)
- image = image.resize([x, y], Image.ANTIALIAS)
- try:
- image.save(miniature_filename, image.format, quality=90, optimize=1)
- except:
- image.save(miniature_filename, image.format, quality=90)
-
- return miniature_url
-
-
-register.filter(thumbnail)
-
-
-def clean_thumb(sender, instance, **kwargs):
- if not hasattr(instance, 'image'):
- return
- if not instance.image:
- return
- name, ext = os.path.splitext(os.path.basename(instance.image.name))
- exp = '^%s__\d+x\d+x[0-1]{1}\%s' % (name, ext)
- for file_path in os.listdir(settings.MEDIA_ROOT):
- if re.search(exp, file_path):
- os.unlink(settings.MEDIA_ROOT + file_path)
-
-
-post_save.connect(clean_thumb)
-pre_delete.connect(clean_thumb)