从 Python Flask API 中,我想在单个 API 响应中返回一个图像流和一些文本。
像这样的东西:
{
'Status' : 'Success',
'message': message,
'ImageBytes': imageBytes
}
Run Code Online (Sandbox Code Playgroud)
另外,我想知道什么是最好的格式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
Run Code Online (Sandbox Code Playgroud)
我使用以下实用程序函数将图像转换为 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6742 次 |
| 最近记录: |