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

 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. [UPDATE]Filter to resize a ImageField on demand by rafacdb 5 years, 8 months ago
  2. UPDATED: Django Image Thumbnail Filter by danfairs 6 years, 5 months ago
  3. Filter to resize a ImageField on demand by michelts 7 years ago
  4. iPernity thumbnail helper by sedden 5 years, 5 months ago
  5. Improved many-page pagination by dokterbob 3 years, 7 months 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

#

(Forgotten your password?)