前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Django上传图片生成成缩略图的类

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

原创
作者头像
用户8983410
修改2021-11-03 13:00:33
1.1K0
修改2021-11-03 13:00:33
举报
文章被收录于专栏:代码小技巧分享分析

这段代码通过pil生成缩略图,主要通过save函数保存缩略图,自定义了图片的保存位置和原图片位置,可以自己更改,可以指定缩略图的大小。

代码语言:javascript
复制
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)</pre> 

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档