from django.conf import settings from django import template import os, os.path import Image from django.utils.safestring import mark_safe register = template.Library() def src_and_size(filename, args=''): if filename is None: return '' if filename.startswith(settings.MEDIA_URL): full_filename = filename[len(settings.MEDIA_URL):] full_filename = os.path.join(settings.MEDIA_ROOT, full_filename) if not os.path.exists(full_filename): print "Warning, miniature not found: %s" % filename return image = Image.open(full_filename) return mark_safe('width="%s" height="%s" src="%s"' % (image.size[0], image.size[1], filename)) register.filter(src_and_size) def thumbnail(filename, args=''): def get_basename(filename): basename = extension = '' arr = filename.rsplit('.', 1) basename = arr[0] if len(arr)>1: extension = arr[1] return basename,extension if filename=='': return width = None height = None if filename.startswith(settings.MEDIA_URL): filename = filename[len(settings.MEDIA_URL):] basename,extension = get_basename(filename) miniature = basename # +'_t' resizeByWidth = False resizeByHeight = False for arg in args.split(','): arg = arg.strip() key,val = arg.split('=', 1) if key=='width': if not resizeByHeight: resizeByWidth = True width = int(val) miniature+='_w_'+val elif key=='height': if not resizeByWidth: resizeByHeight = True height = int(val) miniature+='_h_'+val if width==None and height==None : raise template.TemplateSyntaxError, "thumbnail filter requires arguments (width and/or height)" miniature += '.'+extension miniature = "%s/._t_%s" % (os.path.dirname(miniature), os.path.basename(miniature)) miniature_filename = os.path.join(settings.MEDIA_ROOT, miniature) miniature_url = os.path.join(settings.MEDIA_URL, miniature) filename = os.path.join(settings.MEDIA_ROOT, filename) if not os.path.exists(filename): print "Warning, miniature not created for non-exising file: %s" % filename return if not os.path.exists(miniature_filename) or (os.path.getmtime(filename) > os.path.getmtime(miniature_filename)): image = Image.open(filename) if resizeByWidth: new_height = int(image.size[1] * width / image.size[0]) if (height is not None) and new_height>height: new_height = height new_width = int(image.size[0] * height / image.size[1]) else: new_width = width elif resizeByHeight: new_width = int(image.size[0] * height / image.size[1]) if (width is not None) and new_width>width: new_width = width new_height = int(image.size[1] * width / image.size[0]) else: new_height = height try: image.thumbnail([new_width,new_height],Image.ANTIALIAS) image.save(miniature_filename, image.format) except IOError, e: print 'DjHDGutils: thumbnail.py: IOError %s for file: %s.' % (e,filename) return return miniature_url register.filter(thumbnail) @register.simple_tag def thumbnail_url(url, width, height): args=[] if width: args.append('width=%s' % width) if height: args.append('height=%s' % height) return thumbnail(url, ",".join(args))