在保存到磁盘之前缩放Django ImageField

时间:2012-11-08 08:32:55

标签: python django python-imaging-library

我想在模型保存到磁盘之前缩放ImageField,但不知何故得到一个不可读的图像。目标是在不将其保存到磁盘的情况下进行扩展。

这是我到目前为止的尝试:

IMAGE_MAX_SIZE = 800, 800
class Picture(models.Model):
    ...
    image = models.ImageField(upload_to='images/%Y/%m/%d/')

    # img is a InMemoryUploadedFile, received from a post upload
    # removing the scale function results in a readable image
    def set_image(self, img):
        self.image = img
        self.__scale_image()

    def __scale_image(self):
        img = Image.open(StringIO(self.image.read()))
        img.thumbnail(IMAGE_MAX_SIZE, Image.ANTIALIAS)
        imageString = StringIO()
        img.save(imageString, img.format)
        self.image.file = InMemoryUploadedFile(imageString, None, self.image.name, self.image.file.content_type, imageString.len, None)

我没有收到错误,但无法正确显示生成的图像。任何想法如何纠正这个?

由于 西蒙

2 个答案:

答案 0 :(得分:1)

我很亲密,但并不完全。此功能现在可以正常工作,并且在缩放过程中任何时候图像都不会保存到光盘。

IMAGE_MAX_SIZE = 800, 800
class Picture(models.Model):
    ...
    image = models.ImageField(upload_to='images/%Y/%m/%d/')

    # img is a InMemoryUploadedFile, received from a post upload
    def set_image(self, img):
        self.image = img
        self.__scale_image(self.image, IMAGE_MAX_SIZE)

    def __scale_image(self, image, size):
        image.file.seek(0) # just in case
        img = Image.open(StringIO(image.file.read()))
        img.thumbnail(size, Image.ANTIALIAS)
        imageString = StringIO()
        img.save(imageString, img.format)

        # for some reason content_type is e.g. 'images/jpeg' instead of 'image/jpeg'
        c_type = image.file.content_type.replace('images', 'image')
        imf = InMemoryUploadedFile(imageString, None, image.name, c_type, imageString.len, None)
        imf.seek(0)
        image.save(
                image.name,
                imf,
                save=False
            )

答案 1 :(得分:0)

最好使用sorl-thumbnail。