这段代码通过pil生成缩略图,主要通过save函数保存缩略图,自定义了图片的保存位置和原图片位置,可以自己更改,可以指定缩略图的大小。
from pil import image
from cstringio import stringio
from django.core.files.uploadedfile import simpleuploadedfile
class photo(models.model):
#from sharejs.com
title = models.charfield(max_length = 100)
image = models.imagefield(upload_to ="photos/originals/%y/%m/")
image_height = models.integerfield()
image_width = models.integerfield()
thumbnail = models.imagefield(upload_to="photos/thumbs/%y/%m/")
thumbnail_height = models.integerfield()
thumbnail_width = models.integerfield()
caption = models.charfield(max_length = 250, blank =true)
def __str__(self):
return "%s"%self.title
def __unicode__(self):
return self.title
def save(self, force_update=false, force_insert=false, thumb_size=(180,300)):
image = image.open(self.image)
if image.mode not in ('l', 'rgb'):
image = image.convert('rgb')
# save the original size
self.image_width, self.image_height = image.size
image.thumbnail(thumb_size, image.antialias)
# save the thumbnail to memory
temp_handle = stringio()
image.save(temp_handle, 'png')
temp_handle.seek(0) # rewind the file
# save to the thumbnail field
suf = simpleuploadedfile(os.path.split(self.image.name)[-1],
temp_handle.read(),
content_type='image/png')
self.thumbnail.save(suf.name '.png', suf, save=false)
self.thumbnail_width, self.thumbnail_height = image.size
# save the image object
super(photo, self).save(force_update, force_insert)
贝壳116