python-3.x - 如何动态响应 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'
有人能帮助我吗?
解决方案
使用io.BytesIO()
而不是io.StringIO()
. (来自这个答案。)
推荐阅读
- java - getLastKnownLocation 导致我的应用程序崩溃
- mysql - 由于错误代码 1236,无法启动 debezium MySQL 连接器
- javascript - 强制socketio事件监听器等待回调
- solr - Solr 管理服务器 - 基本查询请求不返回结果
- jquery - 如何使用 Flask 和 JSON 变量显示带有 Tabulator 的表格
- cytoscape.js - Cytoscape popper 元素总是溢出
- arrays - 音乐剧本解决方案
- oracle - 如何将包括地理空间数据在内的 Oracle 数据导出为 CSV?
- python - 向表格小部件添加信息时出现问题
- openmp - openmp taskwait 是否释放任务正在运行的核心?