2017-09-25 66 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'))