import os import os.path import re import Image from django.template import Library register = Library() def thumbnail(file, size='100x100x1'): # defining the size x, y, ratio = [int(x) for x in size.split('x')] # defining the filename and the miniature filename filehead, filetail = os.path.split(file.path) basename, format = os.path.splitext(filetail) miniature = basename + '_' + size + format filename = file.path miniature_filename = os.path.join(filehead, miniature) filehead, filetail = os.path.split(file.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): image = Image.open(filename) if ratio == 0: image = image.resize([x, y], Image.ANTIALIAS) else: image.thumbnail([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) # CLEAN CODE (CHANGE THE VARIABLES) from os import listdir, remove from os.path import basename, splitext from re import search from django.db.models.signals import post_save, pre_delete from eduardomillan import settings def clean_thumb(sender, instance, **kwargs): name, ext = splitext(basename(instance.IMAGE_FIELD.name)) exp = '^%s_\d+x\d+x[0-1]{1}\%s' % (name, ext) for file_path in listdir(settings.MEDIA_ROOT): if search(exp, file_path): remove(settings.MEDIA_ROOT + file_path) post_save.connect(clean_thumb, sender=FIELD_MODEL) pre_delete.connect(clean_thumb, sender=FIELD_MODEL)