[英]How to return image stream and text as JSON response from Python Flask API
从 Python Flask API,我想在单个 API 响应中返回一个图像流和一些文本。
像这样的东西:
{
'Status' : 'Success',
'message': message,
'ImageBytes': 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
我使用以下实用程序函数将图像转换为 ByteArry 并作为 JSON 输出中的参数之一返回。
def getImageBytes(filePath):
img = Image.open(filePath, mode='r')
imgByteArr = io.BytesIO()
imgByteArr = imgByteArr.getvalue()
imgByteArr = base64.encodebytes(imgByteArr).decode('ascii')
return imgByteArr
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.