首页 > 解决方案 > 如何动态响应 Cherrypy 中的 PIL 图像(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'

有人能帮助我吗?

标签: python-3.xpython-imaging-librarycherrypy

解决方案


使用io.BytesIO()而不是io.StringIO(). (来自这个答案。)


推荐阅读