Size: 2344
Comment:
|
Size: 2444
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 28: | Line 28: |
image = Image.open(self.photo.name) | # image = Image.open(self.photo.name) # as of Django 1.2 at least, .name doesn't work. image = Image.open(self.photo) |
[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 # as of Django 1.2 at least, .name doesn't work.
23 image = Image.open(self.photo)
24
25 # Convert to RGB if necessary
26 # Thanks to Limodou on DjangoSnippets.org
27 # http://www.djangosnippets.org/snippets/20/
28 if image.mode not in ('L', 'RGB'):
29 image = image.convert('RGB')
30
31 # We use our PIL Image object to create the thumbnail, which already
32 # has a thumbnail() convenience method that contrains proportions.
33 # Additionally, we use Image.ANTIALIAS to make the image look better.
34 # Without antialiasing the image pattern artifacts may result.
35 image.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS)
36
37 # Save the thumbnail
38 temp_handle = StringIO()
39 image.save(temp_handle, 'png')
40 temp_handle.seek(0)
41
42 # Save to the thumbnail field
43 suf = SimpleUploadedFile(os.path.split(self.photo.name)[-1],
44 temp_handle.read(), content_type='image/png')
45 self.thumbnail.save(suf.name+'.png', suf, save=False)
46
47 # Save this photo instance
48 super(Photo, self).save()
49
50 class Admin:
51 pass
52
53 def __str__(self):
54 return self.title