[Python] Django上传图片生成成缩略图的类 →→→→→进入此内容的聊天室

来自 , 2020-10-27, 写在 Python, 查看 159 次.
URL http://www.code666.cn/view/c34a7191
  1. from PIL import Image
  2. from cStringIO import StringIO
  3. from django.core.files.uploadedfile import SimpleUploadedFile
  4.  
  5. class Photo(models.Model):
  6.     #from sharejs.com
  7.     title = models.CharField(max_length = 100)
  8.     image = models.ImageField(upload_to ="photos/originals/%Y/%m/")
  9.     image_height = models.IntegerField()
  10.     image_width = models.IntegerField()
  11.     thumbnail = models.ImageField(upload_to="photos/thumbs/%Y/%m/")
  12.     thumbnail_height = models.IntegerField()
  13.     thumbnail_width = models.IntegerField()
  14.     caption = models.CharField(max_length = 250, blank =True)
  15.    
  16.     def __str__(self):
  17.         return "%s"%self.title
  18.    
  19.     def __unicode__(self):
  20.         return self.title
  21.        
  22.     def save(self, force_update=False, force_insert=False, thumb_size=(180,300)):
  23.  
  24.         image = Image.open(self.image)
  25.        
  26.         if image.mode not in ('L', 'RGB'):
  27.             image = image.convert('RGB')
  28.            
  29.         # save the original size
  30.         self.image_width, self.image_height = image.size
  31.        
  32.         image.thumbnail(thumb_size, Image.ANTIALIAS)
  33.        
  34.         # save the thumbnail to memory
  35.         temp_handle = StringIO()
  36.         image.save(temp_handle, 'png')
  37.         temp_handle.seek(0) # rewind the file
  38.        
  39.         # save to the thumbnail field
  40.         suf = SimpleUploadedFile(os.path.split(self.image.name)[-1],
  41.                                  temp_handle.read(),
  42.                                  content_type='image/png')
  43.         self.thumbnail.save(suf.name+'.png', suf, save=False)
  44.         self.thumbnail_width, self.thumbnail_height = image.size
  45.        
  46.         # save the image object
  47.         super(Photo, self).save(force_update, force_insert)
  48. #//python/8672

回复 "Django上传图片生成成缩略图的类"

这儿你可以回复上面这条便签

captcha