我想从 Python Flask API 返回图像流以及单个 API 响应中的一些文本。
像这样的东西:
{
'Status' : 'Success',
'message': message,
'ImageBytes': imageBytes
}
另外,我想知道什么是最好的格式imageBytes
,以便客户端应用程序(Java / JQuery)可以解析和重建图像。
如果上述方法不正确,请提出更好的方法。
以下对我有用:
import io
from base64 import encodebytes
from PIL import Image
# from flask import jsonify
def get_response_image(image_path):
pil_img = Image.open(image_path, mode='r') # reads the PIL image
byte_arr = io.BytesIO()
pil_img.save(byte_arr, format='PNG') # convert the PIL image to byte array
encoded_img = encodebytes(byte_arr.getvalue()).decode('ascii') # encode as base64
return encoded_img
# server side code
image_path = 'images/test.png' # point to your image location
encoded_img = get_response_image(image_path)
my_message = 'here is my message' # create your message as per your need
response = { 'Status' : 'Success', 'message': my_message , 'ImageBytes': encoded_img}
# return jsonify(response) # send the result to client
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)