Alex Rivera | Logout

Image resizing with django?

Asked 2009-07-22T12:32:54.950
14

I'm new to Django (and Python) and I have been trying to work out a few things myself, before jumping into using other people's apps. I'm having trouble understanding where things 'fit' in the Django (or Python's) way of doing things. What I'm trying to work out is how to resize an image, once it's been uploaded. I have my model setup nicely and plugged into the admin, and the image uploads fine to the directory:

from django.db import models

# This is to list all the countries
# For starters though, this will be just United Kingdom (GB)
class Country(models.Model):
    name = models.CharField(max_length=120, help_text="Full name of country")
    code = models.CharField(max_length=2, help_text="This is the ISO 3166 2-letter country code (see: http://www.theodora.com/country_digraphs.html)")
    flag = models.ImageField(upload_to="images/uploaded/country/", max_length=150, help_text="The flag image of the country.", blank=True)

    class Meta:
        verbose_name_plural = "Countries"

    def __unicode__(self):
        return self.name

The thing I'm now having trouble with is taking that file and making a new file into a thumbnail. Like I say, I'd like to know how to do it without using others' apps (for now). I have got this code from DjangoSnippets:

from PIL import Image
import os.path
import StringIO

def thumbnail(filename, size=(50, 50), output_filename=None):
    image = Image.open(filename)
    if image.mode not in ('L', 'RGB'):
        image = image.convert('RGB')
    image = image.resize(size, Image.ANTIALIAS)

    # get the thumbnail data in memory.
    if not output_filename:
        output_filename = get_default_thumbnail_filename(filename)
    image.save(output_filename, image.format) 
    return output_filename

def thumbnail_string(buf, size=(50, 50)):
    f = StringIO.StringIO(buf)
    image = Image.open(f)
    if image.mode not in ('L', 'RGB'):
        image = image.convert('RGB')
    image = ima
Edit
Report

1 Answer

2

A key question is: when should the thumbnail be generated?

  1. Dynamically when the user requests a thumbnail image?
  2. Or do you want to create a physical disk file whenever a country is INSERTed/UPDATEd in the database.

If (1) I suggest you create a view that maps to url /flagthumbnail/countryid. The view method would then have to:

  1. Get the country instance from the database
  2. Read the flag image into a PIL Image and resize that.
  3. Create (and return) a HTTPResponse with correct content-type and write the PIL Image to the response.

Whenever you need to display a thumbnail flag, just use <a href="/flagthumbnail/countryid">.

If (2), you could connect to Django's django.db.models.signals.post_save signal and in the signal handler create and save a thumbnail file.

answered 2009-07-22T12:51:25.703

Your Answer