小编典典

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

django

我试图将UploadedFile一个PIL Image对象转换为缩略图,然后将Image我的缩略图函数返回的PIL 对象转换为一个File对象。我怎样才能做到这一点?


阅读 439

收藏
2020-03-27

共1个答案

小编典典

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

2020-03-27