Login

Template Tag of Django Image Thumb Creator

Author:
ayang23
Posted:
February 4, 2011
Language:
Python
Version:
1.2
Score:
2 (after 2 ratings)

You can save these codes into a templatetag file in your django app. Then use codes like these in your template files:


{% load *yourtags* %}
...
<img src="{% thumb *yourmodel.picturefield* 200 300 0 %}"/>
<img src="{% thumb *yourmodel.picturefield* 500 400 yes %}"/>
...

The parameters are:

imagefield ImageField
width Integer
height Integer
rescale [1, yes, true, 0, no, false]

Some codes come from <djangosnippets.org>

 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import os
from django import template
from django.db.models.fields.files import ImageFieldFile
import Image as PImage
from urlparse import urljoin
from os import path

register = template.Library()

class NotImageFieldError(ValueError):
    pass

def get_thumb(imagefield, width, height):
    size = width, height
    pathname, filename = path.split(imagefield.path)
    shortname, extname = path.splitext(filename)
    thumbname = '%s-%dx%d%s' % (shortname, width, height, extname)
    p = path.join(pathname, 'thumbs', thumbname)
    if path.isfile(p):
        pass
    else:
        if not path.isdir(path.dirname(p)):
            os.mkdir(path.dirname(p), 0755)
        img = PImage.open(imagefield.path)
        img.thumbnail(size, PImage.ANTIALIAS)
        img.save(p)

    return urljoin(imagefield.url, 'thumbs/' + thumbname)


def get_rescale(imagefield, width, height):
    pathname, filename = path.split(imagefield.path)
    shortname, extname = path.splitext(filename)
    thumbname = '%s-%dx%d%s' % (shortname, width, height, extname)
    p = path.join(pathname, 'rescaled', thumbname)
    if path.isfile(p):
        pass
    else:
        if not path.isdir(path.dirname(p)):
            os.mkdir(path.dirname(p), 0755)
        img = PImage.open(imagefield.path)
        src_width, src_height = img.size
        src_ratio = float(src_width) / float(src_height)
        dst_ratio = float(width) / float(height)

        if dst_ratio < src_ratio:
            crop_height = src_height
            crop_width = crop_height * dst_ratio
            x_offset = float(src_width - crop_width) / 2
            y_offset = 0
        else:
            crop_width = src_width
            crop_height = crop_width / dst_ratio
            x_offset = 0
            y_offset = float(src_height - crop_height) / 3
        img = img.crop((int(x_offset), int(y_offset), int(x_offset+crop_width), int(y_offset+crop_height)))
        img = img.resize((width, height), PImage.ANTIALIAS)
        img.save(p)

    return urljoin(imagefield.url, 'rescaled/' + thumbname)

class ThumbNail(template.Node):
    def __init__(self, imagestr, width, height, rescale=False):
        self.imagestr = template.Variable(imagestr)
        self.width = width
        self.height = height
        self.rescale = rescale

    def render(self, context):
        image = self.imagestr.resolve(context)
        if not isinstance(image, ImageFieldFile):
            raise NotImageFieldError, '%s is not an instance of ImageFieldFile.' % self.imagestr
        if self.rescale:
            self.url = get_rescale(image, self.width, self.height)
        else:
            self.url = get_thumb(image, self.width, self.height)
        return self.url

@register.tag(name='thumb')
def do_thumb(parser, token):
    try:
        tagname, imagestr, widthstr, heightstr, rescalestr = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires exactly 4 arguments" % token.contents.split()[0]
    try:
        width = int(widthstr)
        height = int(heightstr)
        if rescalestr in ('1', 'yes', 'true', 'True'):
            rescale = True
        else:
            rescale = False
    except ValueError:
        raise template.TemplateSyntaxError, 'Arguments error in tag %r' % token.contents.split()[0]
    return ThumbNail(imagestr, width, height, rescale)

        

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

szok (on April 30, 2011):

And as the machine to remove these files in Django-admin?

#

Please login first before commenting.