Login

Auto Generate/Save Thumbnails using Template Filter (scale max_x, max_y, or both)

Author:
ThisbeTom
Posted:
December 9, 2008
Language:
HTML/template
Version:
Not specified
Score:
2 (after 2 ratings)

Couldn't get the original to work, and wanted more functionality (scale on x or y coordinates)

<img src="{{ object.image.url }}" alt="original image">
<img src="{{ object.image|thumbnail:"250w" }}" alt="image resized to 250w x (calculated/scaled)h ">
<img src="{{ object.image|thumbnail:"250h" }}" alt="image resized to (calculated/scaled)w x 250h h ">
<img src="{{ object.image|thumbnail:"250x200" }}" alt="image resized to 250wx200h ">
<img src="{{ object.image|thumbnail }}" alt="image resized to default 200w (or whatever you default it to) format">

Original http://www.djangosnippets.org/snippets/192/ Adapted http://www.djangosnippets.org/snippets/955/ Sampled From: http://batiste.dosimple.ch/blog/2007-05-13-1/ http://vaig.be/2008/05/17/stdimagefield-improved-image-field-for-django/

 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
import os
import Image
from django.template import Library

register = Library()

SCALE_WIDTH = 'w'
SCALE_HEIGHT = 'h'
SCALE_BOTH = 'both'

def scale(max_x, pair):
    x, y = pair
    new_y = (float(max_x) / x) * y
    return (int(max_x), int(new_y))

@register.filter
def thumbnail(file, size='200w'):
    # defining the size
    if (size.lower().endswith('h')):
        mode = 'h'
        size = size[:-1]
        max_size = int(size.strip())
    elif (size.lower().endswith('w')):
        mode = 'w'
        size = size[:-1]
        max_size = int(size.strip())
    else:
        mode = 'both'
        
    # 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)
        image_x, image_y = image.size  
        
        if mode == SCALE_HEIGHT:
            image_y, image_x = scale(max_size, (image_y, image_x))
        elif mode == SCALE_WIDTH:
            image_x, image_y = scale(max_size, (image_x, image_y))
        elif mode == SCALE_BOTH:
            image_x, image_y = [int(x) for x in size.split('x')]
        else:
            raise Exception("Thumbnail size must be in ##w, ##h, or ##x## format.")
            
        image.thumbnail([image_x, image_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

More like this

  1. Bootstrap Accordian by Netplay4 5 years, 10 months ago
  2. Bootstrap theme for django-endless-pagination? by se210 8 years, 10 months ago
  3. Bootstrap theme for django-endless-pagination? by se210 8 years, 10 months ago
  4. Reusable form template with generic view by roldandvg 8 years, 11 months ago
  5. Pagination Django with Boostrap by guilegarcia 9 years, 1 month ago

Comments

phoebebright (on January 6, 2009):

Just what I wanted, thanks. In case the original image does not exist, I added a try and except block around the whole thing so it return a empty string.

def thumbnail(file, size='200w'):

miniature_url=''

try:

    # defining the size
    if (size.lower().endswith('h')):


  ... rest of code ...


except:
    miniature_url=''


return miniature_url

#

Please login first before commenting.