Login

[UPDATE]Filter to resize a ImageField on demand

Author:
rafacdb
Posted:
August 9, 2008
Language:
Python
Version:
.96
Score:
3 (after 3 ratings)

A filter to resize a ImageField on demand, a use case could be:

<img src="{{ object.image.url }}" alt="original image"> 
<img src="{{ object.image|thumbnail }}" alt="image resized to default 104x104 format"> 
<img src="{{ object.image|thumbnail:200x300 }}" alt="image resized to 200x300">

Original http://www.djangosnippets.org/snippets/192/

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

#

Please login first before commenting.