如何将PIL`Image`转换成Django`File`? [英] How do you convert a PIL `Image` to a Django `File`?

查看:389
本文介绍了如何将PIL`Image`转换成Django`File`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 UploadedFile 转换为PIL 图像对象缩略图,然后将PIL 图像对象,我的缩略图功能返回到文件对象。如何做到这一点?

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?

推荐答案

这样做而不必写回文件系统,然后带上文件通过打开的调用回到内存中,是使用StringIO和Django InMemoryUploadedFile。以下是关于您如何执行此操作的快速示例。这假设您已经有一个名为thumb的缩略图像:

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':

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。这让我在一天中更好的部分来正确找到解决方案。

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.

这篇关于如何将PIL`Image`转换成Django`File`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆