Login

Updated Filter to resize a ImageField on demand

Author:
gmandx
Posted:
September 4, 2009
Language:
Python
Version:
1.1
Tags:
filter models thumbnail resize imagefield demand
Score:
0 (after 0 ratings)

Based on http://www.djangosnippets.org/snippets/192/

But this works with Django 1.1 while maintaining the same functionality.

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

register = Library()

def thumbnail(file, size='200x200'):
    """
    Example:
    <img src="object.get_image_url" alt="original image" />
    <img src="object.image|thumbnail" alt="image resized to default 200x200 format" />
    <img src="object.image|thumbnail:"200x300" alt="image resized to 200x300" />

    The filter is applied to a image field (not the image url get from
    get_image_url method of the model), supposing the image filename is
    "image.jpg", it checks if there is a file called "image_200x200.jpg" or
    "image_200x300.jpg" on the second case, if the file isn't there, it resizes
    the original image, finally it returns the proper url to the resized image.
    """

    if file:
        # defining the size
        x, y = [int(x) for x in size.split('x')]
        # defining the filename and the miniature filename
        basename, format = file.path.rsplit('.', 1)
        baseurl, _format = file.url.rsplit('.', 1)

        #miniature = basename + '_' + size + '.' +  format
        #miniature_filename = os.path.join(settings.MEDIA_ROOT, miniature)
        #miniature_url = os.path.join(settings.MEDIA_URL, miniature)

        miniature_filename = basename + '_' + size + '.' +  format
        miniature_url = baseurl + '_' + size + '.' +  format

        # if the image wasn't already resized, resize it
        if not os.path.exists(miniature_filename):
            #print '>>> debug: resizing the image to the format %s!' % size
            image = Image.open(file.path)
            image.thumbnail([x, y]) # generate a 200x200 thumbnail
            image.save(miniature_filename, image.format)
        return miniature_url

    return ''

register.filter(thumbnail)

More like this

  1. [UPDATE]Filter to resize a ImageField on demand by rafacdb 6 years, 11 months ago
  2. Updated Filter to resize a ImageField on demand (ver.2) by rawjam 5 years, 6 months ago
  3. Filter to resize a ImageField on demand by michelts 8 years, 3 months ago
  4. [UPDATE]Filter to resize a ImageField on demand + RATIO OPTION + CLEANUP by karlsberg 4 years, 11 months ago
  5. Download an image using requests, resize it using PIL, and save it to a model ImageField. by stewx 4 months, 1 week ago

Comments

dmlodecki (on July 21, 2010):

This works great. Consider changing image.thumbnail([x, y]) to image.thumbnail([x, y], Image.ANTIALIAS) for higher-quality resizes.

#

Please login first before commenting.