我正在尝试转换UploadedFile
到 PILImage
对象对其进行缩略图,然后转换 PILImage
我的缩略图函数返回到的对象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-storages 上传到 S3。我花了一天的时间才在这里正确找到解决方案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)