简体   繁体   English

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

[英]How to return image stream and text as JSON response from Python Flask API

From a Python Flask API, I want to return an image stream and also some text in a single API response.从 Python Flask API,我想在单个 API 响应中返回一个图像流和一些文本。

Something like this:像这样的东西:

{
  'Status' : 'Success',
  'message': message,
  'ImageBytes': imageBytes
}

Also, I would like to know what would be the best format to use for imageBytes , so that the client applications (Java / JQuery) can parse and reconstruct the image.另外,我想知道用于imageBytes的最佳格式是imageBytes ,以便客户端应用程序(Java/JQuery)可以解析和重建图像。

If the above approach is not correct, please suggest a better approach.如果上述方法不正确,请提出更好的方法。

The following worked for me:以下对我有用:

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

I used the following utility function to convert the image into ByteArry and returned as one of the parameter in my JSON output.我使用以下实用程序函数将图像转换为 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM