以下代码会在图片被保存后,制作出一个缩略图:
```python from PIL import Image size = (128, 128)
with Image.open('image.jpg') as im: im.thumbnail(size) im.save('thumbnail.jpg') ```
```python from PIL import Image size = (128, 128)
with Image.open('image.jpg') as im: im.thumbnail(size) im.save('thumbnail.jpg') ```
class Image(models.Model):
image = models.ImageField(upload_to='images')
thumbnail = models.ImageField(upload_to='images/thumbnails', editable=False)
def save(self, *args, **kwargs):
super(Image, self).save(*args, **kwargs)
if self.image:
from PIL import Image as ImageObj
from cStringIO import StringIO
from django.core.files.uploadedfile import SimpleUploadedFile
try:
# thumbnail
THUMBNAIL_SIZE = (160, 160) # dimensions
image = ImageObj.open(self.image)
# Convert to RGB if necessary
if image.mode not in ('L', 'RGB'): image = image.convert('RGB')
# create a thumbnail + use antialiasing for a smoother thumbnail
image.thumbnail(THUMBNAIL_SIZE, ImageObj.ANTIALIAS)
# fetch image into memory
temp_handle = StringIO()
image.save(temp_handle, 'png')
temp_handle.seek(0)
# save it
file_name, file_ext = os.path.splitext(self.image.name.rpartition('/')[-1])
suf = SimpleUploadedFile(file_name + file_ext, temp_handle.read(), content_type='image/png')
self.thumbnail.save(file_name + '.png', suf, save=False)
except ImportError:
pass
一切运作良好,原始图像和缩略图都已上传,并且图像被分配了正确的路径。
唯一的问题是缩略图没有被分配新创建的缩略图的路径-在数据库中为空。我已经阅读了文档,并且看起来如果我使用save=True保存缩略图,它应该可以解决我的问题:
self.thumbnail.save(file_name + '.png', suf, save=True)
然而,这样做会引发以下问题:
Django Version: 1.3.1
Exception Type: IOError
Exception Value:
cannot identify image file
我无法弄清楚自己做错了什么。