简体   繁体   中英

Scale Django ImageField before saving to disk

I would like to scale an ImageField before the model gets saved to the disk, but somehow get an unreadable image out. The goal is to scale it without ever saving it to the disk.

This is my attempt so far:

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)

I'm not getting an error, but the resulting image can not be displayed correctly. Any ideas how to correct this?

Thanks Simon

I was close, but not quite there. This function works now fine and the image does not get saved to the disc at any point during the scaling.

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
            )

最好使用sorl-thubnail。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM