Django上传图片生成成缩略图的类,,这段代码通过pil生成缩
Django上传图片生成成缩略图的类,,这段代码通过pil生成缩
这段代码通过pil生成缩略图,主要通过save函数保存缩略图,自定义了图片的保存位置和原图片位置,可以自己更改,可以指定缩略图的大小。
from PIL import Imagefrom cStringIO import StringIOfrom 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)
相关内容
- python获取图片元数据的代码,,exif-py是一个纯p
- python每隔N秒运行指定的函数程序,python每隔,一个类似
- 一个python的2048简单实现,python2048,# -*- coding
- 更加高级的阶乘,高级阶乘,f = lambda x
- python实现爬图,不要再爬妹子图了,太没品了,python妹
- python实现爬图,不要再爬妹子图了,太没品了,python妹
- scrapy在采集网页时使用随机user-agent的方法,scrapyuser-
- python collection模块中几种数据结构(Counter、OrderedDict、
- word文档批量修改,word文档,#!/usr/bin/p
- BeautifulSoup模块的简单使用,beautifulsoup模块,可以通过
评论关闭