如何动态响应Cherrypy中的PIL图像(Python3)?

时间:2018-06-08 12:18:07

标签: python-3.x python-imaging-library cherrypy

似乎任务很简单,但......

我有简单的PIL.Image对象。如何动态地使用此图像进行Cherrypy响应?

def get_image(self, data_id):
    cherrypy.response.headers['Content-Type'] = 'image/png'
    img = PIL.Image.frombytes(...)
    buffer = io.StringIO()
    img.save(buffer, 'PNG')
    return buffer.getvalue()

这段代码告诉我:

500 Internal Server Error
The server encountered an unexpected condition which prevented it from fulfilling the request.

Traceback (most recent call last):
  File "C:\Users\Serge\AppData\Local\Programs\Python\Python36\lib\site-packages\cherrypy\_cprequest.py", line 631, in respond
    self._do_respond(path_info)
  File "C:\Users\Serge\AppData\Local\Programs\Python\Python36\lib\site-packages\cherrypy\_cprequest.py", line 690, in _do_respond
    response.body = self.handler()
  File "C:\Users\Serge\AppData\Local\Programs\Python\Python36\lib\site-packages\cherrypy\_cpdispatch.py", line 60, in __call__
    return self.callable(*self.args, **self.kwargs)
  File "D:\Dev\Bf\webapp\controllers\calculation.py", line 69, in get_image
    img.save(buffer, 'PNG')
  File "C:\Users\Serge\AppData\Local\Programs\Python\Python36\lib\site-packages\PIL\Image.py", line 1930, in save
    save_handler(self, fp, filename)
  File "C:\Users\Serge\AppData\Local\Programs\Python\Python36\lib\site-packages\PIL\PngImagePlugin.py", line 731, in _save
    fp.write(_MAGIC)
TypeError: string argument expected, got 'bytes'

有人能帮助我吗?

1 个答案:

答案 0 :(得分:1)

使用io.BytesIO()代替io.StringIO()。 (来自this回答。)