Django: resize image before upload

后端 未结 3 1974
我寻月下人不归
我寻月下人不归 2020-12-01 11:33

I want to resize image(Pillow) before upload, I write code below but doesn\'t work! and get error:

AttributeError at /m

相关标签:
3条回答
  • 2020-12-01 12:08
    from PIL import Image
    from io import BytesIO
    from django.core.files.base import ContentFile
    from resizeimage import resizeimage
    
    class SomeModel(models.Model):
        image = models.ImageField(upload_to=your_get_file_path_callback)
    
        def save(self, *args, **kwargs):
            pil_image_obj = Image.open(self.image)
            new_image = resizeimage.resize_width(pil_image_obj, 100)
    
            new_image_io = BytesIO()
            new_image.save(new_image_io, format='JPEG')
    
            temp_name = self.image.name
            self.image.delete(save=False)  
    
            self.image.save(
                temp_name,
                content=ContentFile(new_image_io.getvalue()),
                save=False
            )
    
            super(SomeModel, self).save(*args, **kwargs)
    

    P.S. for resizing I've used 'python-image-resize' https://github.com/charlesthk/python-resize-image

    0 讨论(0)
  • 2020-12-01 12:11

    For image resizing you can make use of djanof easy thumbnail library.

    Below is the sample code,that i have used in my project

    options = {'size': (200, 200), 'crop': True}
    thumb_url =get_thumbnailer(image path).get_thumbnail(options).url
    

    For reference https://github.com/SmileyChris/easy-thumbnails

    0 讨论(0)
  • 2020-12-01 12:21

    There have been some helpful answers, but you might want to understand what is going on with your current code.

    Your code raises that exception because of this line :

    request.FILES['docfile'] = imga
    

    What is wrong with that ? You are affecting a pillow Image object to a django ImageField element. Those are two different types and when you call you Document constructor, it might expect to find a file form field that contains a _committed attribute.

    0 讨论(0)
提交回复
热议问题