如何从Python Flask API返回图像流和文本作为JSON响应 [英] How to return image stream and text as JSON response from Python Flask API

查看:166
本文介绍了如何从Python Flask API返回图像流和文本作为JSON响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过Python Flask API在单个API响应中返回图像流以及一些文本.

From a Python Flask API, I want to return an image stream and also some text in a single API response.

类似这样的东西:

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

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

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.

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

If the above approach is not correct, please suggest a better approach.

推荐答案

以下内容对我有用:

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

这篇关于如何从Python Flask API返回图像流和文本作为JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆