当我上传图片时,Django用PIL创建缩略图

时间:2015-11-17 09:10:04

标签: python django python-imaging-library


我在我的网站上使用django-dropbox进行图像存储 当我上传图像时,我想自动创建缩略图并保存 我尝试了不同的方法,但没有成功 任何帮助将是apreciated
我得到这个异常错误:
无法识别图像文件
这是代码:

class Product(models.Model):
    image = models.ImageField(upload_to='images', storage=STORAGE, null=True, blank=True)
    thumb = models.ImageField(upload_to='thumbs', storage=STORAGE, null=True, blank=True)

    def __unicode__(self):
        return "%s,%s" %(self.id,self.title)

    def save(self):
        # create a thumbnail
        self.create_thumbnail()
        super(Product, self).save()
    def create_thumbnail(self):
        # create a thumbnail
        #self.create_thumbnail()
        from PIL import Image
        from cStringIO import StringIO
        from django.core.files.uploadedfile import SimpleUploadedFile
        import os
        try:
            DJANGO_TYPE = self.image.file.content_type
            print DJANGO_TYPE
            if DJANGO_TYPE == 'image/jpeg':
                PIL_TYPE = 'jpeg'
                FILE_EXTENSION = 'jpg'
            elif DJANGO_TYPE == 'image/png':
                PIL_TYPE = 'png'
                FILE_EXTENSION = 'png'
            else:
                print error
            print "Working1"
            print StringIO(self.image.read())
            im = Image.open(StringIO(self.image.read()))
            size = 128, 128
            im.thumbnail(size, Image.ANTIALIAS)
             # Save the thumbnail
            print "Working2"
            temp_handle = StringIO()
            im.save(temp_handle, PIL_TYPE)
            temp_handle.seek(0)
            # Save image to a SimpleUploadedFile which can be saved into
            # ImageField
            print "Working3"
            suf = SimpleUploadedFile(os.path.split(self.image.name)[-1],
            temp_handle.read(), content_type=DJANGO_TYPE)
            # Save SimpleUploadedFile into image field
            self.thumb.save('%s_thumbnail.%s'%(os.path.splitext(suf.name)[0],FILE_EXTENSION), suf, save=True)
            print "Working4"
        except Exception as e:
            print e

0 个答案:

没有答案