How to resize the new uploaded images using PIL before saving?

后端 未结 6 576
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 20:28

I want to resize the new images in a height and width of 800px and save them. And the app mustn\'t store the real image. Any help?

This is my code, it saves the orig

6条回答
  •  清歌不尽
    2020-12-13 21:05

    here is what worked for me, inspired a little from django-resized

    @receiver(pre_save, sender=MyUser)
    @receiver(pre_save, sender=Gruppo)
    def ridimensiona_immagine(sender, instance=None, created=False, **kwargs):
        foto = instance.foto
    
        foto.file.seek(0)
        thumb = PIL.Image.open(foto.file)
        thumb.thumbnail((
            200, 
            200
            ), PIL.Image.ANTIALIAS)
    
    
        buffer = StringIO.StringIO()
        thumb.save(buffer, "PNG")
        image_file = InMemoryUploadedFile(buffer, None, 'test.png', 'image/png', buffer.len, None)
    
        instance.foto.file = image_file
    

提交回复
热议问题