加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Django上传图片生成成缩略图的类

发布时间:2020-05-25 00:12:42 所属栏目:Python 来源:互联网
导读:Django上传图片生成成缩略图的类

下面是脚本之家 jb51.cc 通过网络收集整理的代码片段。

脚本之家小编现在分享给大家,也给大家做个参考。

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)

以上是脚本之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读