2017-09-25 70 views
0

我有一个Tornado网络服务,它带有一个API调用,它应该接受图像并将其中的某些片段返回给客户端。使用Python Tornado在帖子响应中发送多个图片

我已经成功地发送单个图像返回给客户端像这样的不同的API调用:

byteIO = io.BytesIO() 
Image.fromarray(preprocessedImg).save(byteIO, 'PNG') 
self.write(byteIO.getvalue()) 
self.set_header("Content-type", "image/png") 

我然后试图发送多张图片是这样的:

results = {} 
# changes the segments to raw image data 
for key, segment in segments.items(): 
    byteIO = io.BytesIO() 
    Image.fromarray(segment).save(byteIO, 'PNG') 
    results[key] = byteIO.getvalue() 
# sends the segments to the client 
self.write(results) 
# self.set_header("Content-type", "image/png") 

这引起了一个错误“....... x0c”\ x91 \ t \ x00 \ x00 \ x00 \ x00IEND \ xaeB` \ x82'不是JSON可序列化的 “ 当self.set_header不是已注释掉

将多个图像按键发送到客户端的正确方法是什么?

+0

尝试: '结果[键] = STR(。byteIO.getvalue()进行解码( “UTF-8”))' – harshil9968

+0

字节流不是字符串,https://stackoverflow.com/questions/ 606191/convert-bytes-to-a-python-string – harshil9968

+0

我得到“UnicodeDecodeError:'utf-8'编解码器无法解码位置0中的字节0x89:无效起始字节” – Fuseques

回答

0

字节流不是JSON可串行化字符串,通过解码将字节流转换为字符串。

results[key] = str(byteIO.getvalue().decode("utf-8",errors='replace'))