Django上傳圖片生成成縮略圖的類
這段代碼通過pil生成縮略圖,主要通過save函數保存縮略圖,自定義了圖片的保存位置和原圖片位置,可以自己更改,可以指定縮略圖的大小。
from PIL import Image from cStringIO import StringIO from django.core.files.uploadedfile import SimpleUploadedFileclass 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)</pre>
本文由用戶 e2ex 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!