0

我想在模型保存到磁盘之前缩放一个 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)

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

谢谢西蒙

4

2 回答 2

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
            )
于 2012-11-09T00:21:20.210 回答
0

最好使用 sorl-thubnail。

于 2012-11-08T12:22:43.400 回答