我想在模型保存到磁盘之前缩放一个 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)
我没有收到错误,但生成的图像无法正确显示。任何想法如何纠正这个问题?
谢谢西蒙