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

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

问题描述

我正在尝试将 UploadedFile 转换为 PIL Image 对象以对其进行缩略图,然后转换我的 PIL Image 对象缩略图函数返回到 File 对象.我该怎么做?

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?

推荐答案

无需写回文件系统,然后通过 open 调用将文件带回内存的方法是利用 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天全站免登陆