[Django1.0]에서 이미지 썸네일 만들기

[http://code.djangoproject.com/wiki/ThumbNails 썸네일 만드는 다양한 방법들]을 참고할 수 있는데, 그 가운데 [http://superjared.com/entry/django-quick-tips-2-image-thumbnails/ 원본저장시 하나의 썸네일을 동시저장]하는 방법이 간편한 방법이라 할만하다. 하지만, 1.0에서는 동작하지 아니함. 1.0을 위해서는 아래와 같아야 함.

   1 from django.db import models
   2 
   3 class Photo(models.Model):
   4     """
   5     A photo for my site
   6     """
   7     title = models.CharField(maxlength=50)
   8     photo = models.ImageField(upload_to="photos/")
   9     thumbnail = models.ImageField(upload_to="thumbnails/", editable=False)
  10     
  11     def save(self):
  12         from PIL import Image
  13         from cStringIO import StringIO
  14         from django.core.files.uploadedfile import SimpleUploadedFile
  15     
  16         # Set our max thumbnail size in a tuple (max width, max height)
  17         THUMBNAIL_SIZE = (50, 50)
  18     
  19         # Open original photo which we want to thumbnail using PIL's Image
  20         # object
  21         image = Image.open(self.photo.name)
  22     
  23         # Convert to RGB if necessary
  24         # Thanks to Limodou on DjangoSnippets.org
  25         # http://www.djangosnippets.org/snippets/20/
  26         if image.mode not in ('L', 'RGB'):
  27             image = image.convert('RGB')
  28     
  29         # We use our PIL Image object to create the thumbnail, which already
  30         # has a thumbnail() convenience method that contrains proportions.
  31         # Additionally, we use Image.ANTIALIAS to make the image look better.
  32         # Without antialiasing the image pattern artifacts may result.
  33         image.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS)
  34     
  35         # Save the thumbnail
  36         temp_handle = StringIO()
  37         image.save(temp_handle, 'png')
  38         temp_handle.seek(0)
  39 
  40         # Save to the thumbnail field
  41         suf = SimpleUploadedFile(os.path.split(self.photo.name)[-1],
  42                 temp_handle.read(), content_type='image/png')
  43         self.thunbnail.save(suf.name+'.png', suf, save=False)
  44         
  45         # Save this photo instance
  46         super(Photo, self).save()
  47 
  48     class Admin:
  49         pass
  50 
  51     def __str__(self):
  52         return self.title
web biohackers.net