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

前端 未结 7 1363
無奈伤痛
無奈伤痛 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:42

    I've had to do this in a few steps, imagejpeg() in php requires a similar process. Not to say theres no way to keep things in memory, but this method gives you a file reference to both the original image and thumb (usually a good idea in case you have to go back and change your thumb size).

    1. save the file
    2. open it from filesystem with PIL,
    3. save to a temp directory with PIL,
    4. then open as a Django file for this to work.

    Model:

    class YourModel(Model):
        img = models.ImageField(upload_to='photos')
        thumb = models.ImageField(upload_to='thumbs')
    

    Usage:

    #in upload code
    uploaded = request.FILES['photo']
    from django.core.files.base import ContentFile
    file_content = ContentFile(uploaded.read())
    new_file = YourModel() 
    #1 - get it into the DB and file system so we know the real path
    new_file.img.save(str(new_file.id) + '.jpg', file_content)
    new_file.save()
    
    from PIL import Image
    import os.path
    
    #2, open it from the location django stuck it
    thumb = Image.open(new_file.img.path)
    thumb.thumbnail(100, 100)
    
    #make tmp filename based on id of the model
    filename = str(new_file.id)
    
    #3. save the thumbnail to a temp dir
    
    temp_image = open(os.path.join('/tmp',filename), 'w')
    thumb.save(temp_image, 'JPEG')
    
    #4. read the temp file back into a File
    from django.core.files import File
    thumb_data = open(os.path.join('/tmp',filename), 'r')
    thumb_file = File(thumb_data)
    
    new_file.thumb.save(str(new_file.id) + '.jpg', thumb_file)
    
    0 讨论(0)
提交回复
热议问题