代码之家  ›  专栏  ›  技术社区  ›  Serge

如何在cherrypy(python3)中动态响应pil图像?

  •  0
  • Serge  · 技术社区  · 6 年前

    任务似乎很简单,但是…

    我有一个简单的图片对象。如何用这个图像动态地做出樱桃般的反应?

    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 回复  |  直到 6 年前
        1
  •  1
  •   Andriy Makukha    6 年前

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