Tornado and PIL: open image from headers

python, python-2.7, python-imaging-library, tornado

Solution

PIL documentation states that we can provide a file name or a file-like object to `open()`. So we can use `StringIO` to provide PIL a file-like object. Example applied to your code:

from PIL import Image
from io import StringIO

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

Problem

My Tornado app receive the image in headers. So, I want to re-size it and store it. But I have trouble with opening image - to create PIL object I must have the file with image and pass the name of file to open() method of Image module of PIL. But I only have headers and file info there. Should I create temp file to create Image object? Or maybe some other solutions? ``` 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 ```

Original source