如何从 Python Flask API 返回图像流和文本作为 JSON 响应

use*_*193 5 python flask

从 Python Flask API 中,我想在单个 API 响应中返回一个图像流和一些文本。

像这样的东西:

{
  'Status' : 'Success',
  'message': message,
  'ImageBytes': imageBytes
}
Run Code Online (Sandbox Code Playgroud)

另外,我想知道什么是最好的格式imageBytes,以便客户端应用程序(Java/JQuery)可以解析和重建图像。

如果上述方法不正确,请提出更好的方法。

Haf*_*man 6

以下对我有用:

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)


use*_*193 2

我使用以下实用程序函数将图像转换为 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)