python - Tornado 和 PIL : open image from headers

标签 python python-2.7 python-imaging-library tornado

我的 Tornado 应用程序在标题中接收图像。所以,我想重新调整它的大小并存储它。但是我在打开图像时遇到了问题 - 要创建 PIL 对象,我必须拥有带有图像的文件并将文件名传递给 PIL Image 模块的 open() 方法。但我那里只有标题和文件信息。我应该创建临时文件来创建 Image 对象吗?还是其他一些解决方案?

class ImageHandler(BaseHandler):
    def post(self):
        f = open("out.jpg", "w")
        im = Image.open(self.request.files["ImageUpload"][0]["body"])
        im.save(f, "JPEG")
        self.finish()

TIA!

UPD1 (@bernie)

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/tornado-2.2-py2.7.egg/tornado/web.py", line 988, in _execute
    getattr(self, self.request.method.lower())(*args, **kwargs)
  File "server.py", line 160, in post
    im = Image.open(StringIO(self.request.files["ImageUpload"][0]["body"]))
TypeError: 'module' object is not callable

最佳答案

PIL documentation states我们可以向 open() 提供文件名或类似文件的对象。
所以我们可以使用 StringIO为 PIL 提供一个类文件对象。
适用于您的代码的示例:

from PIL import Image
from io import StringIO

im = Image.open(StringIO(self.request.files["ImageUpload"][0]["body"]))
im.save("out.jpg", "JPEG")

关于python - Tornado 和 PIL : open image from headers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11171789/

相关文章:

python - beautifulsoup 查找某个子项下的所有子项

python - bash 命令通过 cli 正常运行但不在 python 脚本中运行

python - 有没有办法让mariadb与python2.7连接

python - "__get__"参数之一是多余的吗?

python - Subprocess.Popen() => 无输出

python - 如何在基于类的 View 中使用 user_passes_test 装饰器?

Python 2 与 Python 3 导入

python - PIL 剪贴板图像到 Base64 字符串

Python 3.3 TKinter 图像不存在

python - 如何在 Tkinter 消息窗口中自动滚动