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 function returns back into a File
object. How can I do this?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Django __str__ returned non-string (type NoneType)
- Evil ctypes hack in python
The way to do this without having to write back to the filesystem, and then bring the file back into memory via an open call, is to make use of StringIO and Django InMemoryUploadedFile. Here is a quick sample on how you might do this. This assumes that you already have a thumbnailed image named 'thumb':
Let me know if you need more clarification. I have this working in my project right now, uploading to S3 using django-storages. This took me the better part of a day to properly find the solution here.
This is actual working example for python 3.5 and django 1.10
in views.py:
Putting together comments and updates for Python 3+
For those using
django-storages/-redux
to store the image file on S3, here's the path I took (the example below creates a thumbnail of an existing image):Here is an app that can do that: django-smartfields
Make sure to pass
keep_orphans=True
to the field, if you want to keep old files, otherwise they are cleaned up upon replacement.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).
Model:
Usage: