1

Django新手:)

我通过包django-storages使用S3 存储。当我通过管理员上传/更新新图像时,这似乎很完美。

models.py(图像字段)

 image = models.ImageField(
        upload_to=path_and_rename("profiles"),
        height_field="image_height",
        width_field="image_width",
        null=True,
        blank=True,
        editable=True,
        help_text="Profile Picture",
        verbose_name="Profile Picture"
    )
    image_height = models.PositiveIntegerField(null=True, blank=True, editable=False, default="100")
    image_width = models.PositiveIntegerField(null=True, blank=True, editable=False, default="100")

然后我决定我想在上传时调整图像大小,所以尝试在保存覆盖方法中添加以下代码......

def save(self, *args, **kwargs):


        if not self.id and not self.image:
            return

        super(Profile, self).save(*args, **kwargs)


        image = Image.open(self.image).seek(0)
        (width, height) = image.size
        size = ( 100, 100)
        image = image.resize(size, Image.ANTIALIAS)
        image.save(self.image.path)

这是问题所在,这给出了以下错误....

无法识别图像文件

然后我昨天在堆栈上发布了一个问题(我删除了),并且一个用户链接到这个答案Django PIL:IOError Cannot identify image file which I sorta understand(因为图像尚未上传,它还无法读取)。但我不确定这是我的问题!当我收到错误无法识别图像文件时,我可以看到原始文件实际上已上传到 S3 (当然没有调整大小)

记住我是新手,任何人都可以修改我的示例保存方法(并解释)以解决此问题吗?即一种在上传时将新图像调整为 100x100 的方法?

非常感谢

4

2 回答 2

6

如果文件已经写入,则使用存储读取文件,然后调整大小....

def save(self, *args, **kwargs):
        if not self.id and not self.image:
            return

        super(Profile, self).save(*args, **kwargs)


        import urllib2 as urllib
        from cStringIO import StringIO
        from django.core.files.uploadedfile import SimpleUploadedFile

        '''Open original photo which we want to resize using PIL's Image object'''
        img_file = urllib.urlopen(self.image.url)
        im = StringIO(img_file.read())
        resized_image = Image.open(im)




        '''Convert to RGB if necessary'''
        if resized_image.mode not in ('L', 'RGB'):
            resized_image = resized_image.convert('RGB')

        '''We use our PIL Image object to create the resized image, which already
        has a thumbnail() convenicne method that constrains proportions.
        Additionally, we use Image.ANTIALIAS to make the image look better.
        Without antialiasing the image pattern artificats may reulst.'''
        resized_image.thumbnail((100,100), Image.ANTIALIAS)

        '''Save the resized image'''
        temp_handle = StringIO()
        resized_image.save(temp_handle, 'jpeg')
        temp_handle.seek(0)

        ''' Save to the image field'''
        suf = SimpleUploadedFile(os.path.split(self.image.name)[-1].split('.')[0],
                                 temp_handle.read(), content_type='image/jpeg')
        self.image.save('%s.jpg' % suf.name, suf, save=True)
于 2013-03-01T11:06:26.990 回答
0

如果你期望

image.save(self.image.path)

去工作。你不应该打开它

image = Image.open(self.image.path).seek(0)

?

于 2013-03-01T10:16:00.737 回答