您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

您如何将PIL`Image`转换为Django`File`?

您如何将PIL`Image`转换为Django`File`?

无需写回文件系统,然后通过打开调用文件带回内存的方法是利用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。这花了我大部分时间在这里正确地找到解决方案。

Go 2022/1/1 18:40:20 有343人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶