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

How to response with PIL image in Cherrypy dynamically (Python3)?

看起来任务很简单但是...

我有一个简单的 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'

有人可以帮我吗?

使用 io.BytesIO() 而不是 io.StringIO()。 (来自 this 回答。)