During the work at the djangosearch.com I has found articles, which don't exist in Internet anymore. The author of one of this is Andrej Primc, http://k7a.org, whose site is currently empty. I hope that he restores own archives ASAP.
Here is this article.
2007-06-12

My non perfect method is below.

The handle_thumb() function takes two ImageObjects as arguments. 
If a thumbnail doesn't already exist, it uses PIL to generate one and 
save it wherever the original image was saved. The function should 
be invoked in Model's save() function.

The thumbnail is cropped if its aspect ratio isn't the same as the 
image's. Vertical cropping is off-center to the top. That way we're 
likely to keep faces in the frame if a portrait is cropped to a landscape


yourapp/models.py

from django.db import models
from django.conf import settings
import Image, os

def handle_thumb(image_obj, thumb_obj, width, height):
    # create thumbnail
    if image_obj and not thumb_obj:
        thumb = image_obj + ('-t%sx%s.jpg' % (width, height))
        try:
            t = Image.open(settings.MEDIA_ROOT + image_obj)

            w, h = t.size
            if float(w)/h < float(width)/height:
                t = t.resize((width, h*width/w), Image.ANTIALIAS)
            else:
                t = t.resize((w*height/h, height), Image.ANTIALIAS)
            w, h = t.size
            t = t.crop( ((w-width)/2, (h-height)/4, (w-width)/2+width, (h-height)/4+height) )

            t.save(settings.MEDIA_ROOT + thumb, 'JPEG')
            os.chmod(settings.MEDIA_ROOT + thumb, 0666)
            thumb_obj = thumb
        except:
            pass
    return thumb_obj


class Article(models.Model):
    pub_date = models.DateField(db_index = True)
    title = models.CharField(maxlength = 200)
    content = models.TextField(blank = True)    
    image = models.ImageField(upload_to = 'images/%Y%m%d')
    thumb = models.ImageField(upload_to = 'images/%Y%m%d', blank = True, editable = False)

    def save(self):
        self.thumb = handle_thumb(self.image, self.thumb, 118, 88)
        super(Article, self).save()

    def admin_thumb(self):
        if self.thumb:
            return '<a href="%s"><img src="%s" alt=""></a>' % (settings.MEDIA_URL + self.image, settings.MEDIA_URL + self.thumb)
        return None
    admin_thumb.allow_tags = True
    admin_thumb.short_description = 'image'

    class Admin:
        list_display = ('pub_date', 'title', 'admin_thumb',)

8 Votes | Average: 3.8 out of 58 Votes | Average: 3.8 out of 58 Votes | Average: 3.8 out of 58 Votes | Average: 3.8 out of 58 Votes | Average: 3.8 out of 5 (8 votes, average: 3.8 out of 5)
Loading ... Loading ...

Top Posts: