如何将 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
无需写回文件系统,然后通过 open 调用将文件带回内存的方法是使用 StringIO 和 Django InMemoryUploadedFile。以下是有关如何执行此操作的快速示例。这假设您已经有一个名为“thumb”的缩略图:
如果您需要更多说明,请告诉我。我现在正在我的项目中使用此功能,使用 django-storages 上传到 S3。我花了一天的时间才在这里正确找到解决方案。
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':
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.
我必须通过几个步骤来完成此操作,php 中的 imagejpeg() 需要类似的过程。并不是说没有办法将内容保留在内存中,但这种方法为您提供了对原始图像和拇指的文件引用(通常是一个好主意,以防您必须返回并更改拇指大小)。
型号:
用途:
I've had to do this in a few steps, imagejpeg() in php requires a similar process. Not to say theres no way to keep things in memory, but this method gives you a file reference to both the original image and thumb (usually a good idea in case you have to go back and change your thumb size).
Model:
Usage:
这是views.py中python 3.5和django 1.10的实际工作示例
:
This is actual working example for python 3.5 and django 1.10
in views.py:
整理 Python 3+ 的评论和更新
Putting together comments and updates for Python 3+
对于那些像我一样想要将其与 Django 的 FileSystemStorage 结合使用的人来说,需要完成以下内容:
(我在这里所做的是上传图像,将其大小调整为二维并保存两个文件。
utils.py
在views.py中
To complete for those who, like me, want to couple it with Django's
FileSystemStorage
:(What I do here is upload an image, resize it to 2 dimensions and save both files.
utils.py
In views.py
这是一个可以做到这一点的应用程序: django-smartfields
确保传递
keep_orphans=如果您想保留旧文件,则确实如此,否则它们会在替换时被清除。
Here is an app that can do that: django-smartfields
Make sure to pass
keep_orphans=True
to the field, if you want to keep old files, otherwise they are cleaned up upon replacement.对于那些使用 django-storages/-redux 在 S3 上存储图像文件的人,这是我采用的路径(下面的示例创建现有图像的缩略图):
For those using
django-storages/-redux
to store the image file on S3, here's the path I took (the example below creates a thumbnail of an existing image):