[UPDATE]Filter to resize a ImageField on demand

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

register = Library()

def thumbnail(file, size='104x104'):
    # defining the size
    x, y = [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)
        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)

More like this

  1. Filter to resize a ImageField on demand by michelts 6 years, 12 months ago
  2. Auto Generate/Save Thumbnails using Template Filter (scale max_x, max_y, or both) by ThisbeTom 5 years, 4 months ago
  3. iPernity thumbnail helper by sedden 5 years, 5 months ago
  4. UPDATED: Django Image Thumbnail Filter by danfairs 6 years, 5 months ago
  5. load m2m fields objects by dirol 3 years, 10 months ago

Comments

mayroncachina (on October 31, 2008):

para o ultimo exemplo funcionar tem que fazer assim: {{ object.image|thumbnail:"200x300" }}

#

pjs (on January 16, 2009):

Awesome tag! Works perfectly!

#

irfan (on March 31, 2009):

Doesn't work with gof images :S

#

brejoc (on December 2, 2010):

If you are using Umlauts or other weird letters (utf-8) in your filenames you will have to take care of this.

Replace

miniature = basename + '_' + size + format

with

miniature = basename.decode('utf-8') + '_' + size + format

#

(Forgotten your password?)