我试图将一个UploadedFile
转换成一个PIL Image
对象,然后将我的缩略图函数返回的PIL Image
对象转换成File
对象.我该怎么做?
我试图将一个UploadedFile
转换成一个PIL Image
对象,然后将我的缩略图函数返回的PIL Image
对象转换成File
对象.我该怎么做?
要做到这一点而不必写回文件系统,然后通过OPEN调用将文件带回内存,方法是使用StringIO和Django InMemoryUploadedFile.这里有一个关于如何做到这一点的快速示例.这里假设您已经有一个名为"Thumb"的缩略图:
import StringIO
from django.core.files.uploadedfile import InMemoryUploadedFile
# Create a file-like object to write thumb data (thumb data previously created
# using PIL, and stored in variable 'thumb')
thumb_io = StringIO.StringIO()
thumb.save(thumb_io, format='JPEG')
# Create a new Django file-like object to be used in models as ImageField using
# InMemoryUploadedFile. If you look at the source in Django, a
# SimpleUploadedFile is essentially instantiated similarly to what is shown here
thumb_file = InMemoryUploadedFile(thumb_io, None, 'foo.jpg', 'image/jpeg',
thumb_io.len, None)
# Once you have a Django file-like object, you may assign it to your ImageField
# and save.
...
如果你需要更多的澄清,请告诉我.我现在的项目中正在使用django存储上传到S3.这花了我一天的大部分时间才找到解决方案.