How do you convert a PIL `Image` to a Django `File`?

前端 未结 7 1365
無奈伤痛
無奈伤痛 2020-11-27 11:58

I\'m trying to convert an UploadedFile to a PIL Image object to thumbnail it, and then convert the PIL Image object that my thumbnail

7条回答
  •  情歌与酒
    2020-11-27 12:39

    Putting together comments and updates for Python 3+

    from io import BytesIO
    from django.core.files.base import ContentFile
    import requests
    
    # Read a file in
    
    r = request.get(image_url)
    image = r.content
    scr = Image.open(BytesIO(image))
    
    # Perform an image operation like resize:
    
    width, height = scr.size
    new_width = 320
    new_height = int(new_width * height / width)
    img = scr.resize((new_width, new_height))
    
    # Get the Django file object
    
    thumb_io = BytesIO()
    img.save(thumb_io, format='JPEG')
    photo_smaller = ContentFile(thumb_io.getvalue())
    

提交回复
热议问题