基于Flask的API可以返回文件吗 [英] Can a flask-based API return a file

查看:72
本文介绍了基于Flask的API可以返回文件吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Flask编写一个API,该API接受一个文件作为输入,使用OpenCV对其进行操作,然后我想返回该文件.理想情况下,我能够返回文件以及一些元数据(完成操作所花费的时间).

I'm writing an API with Flask that takes a file as input, manipulates it with OpenCV, and then I want to return the file. Ideally I'd be able to return the file along with some meta data (the time it took the operation to complete).

产生要返回的图像的行是:

The line that produces the image I want to return is:

image = cv2.rectangle(图像,起点,终点,颜色,厚度)

理想情况下,我可以直接从内存中返回此值(无需写入临时文件)

Ideally I could return this straight from memory (without ever writing a temporary file)

这有可能吗?

推荐答案

是的,可以做到

from flask import Flask, render_template , request , jsonify
from PIL import Image
import os , io , sys
import numpy as np 
import cv2
import base64

app = Flask(__name__)

start_point = (0, 0) 
end_point = (110, 110) 
color = (255, 0, 0)
thickness = 2

@app.route('/image' , methods=['POST'])
def mask_image():
    file = request.files['image'].read()
    npimg = np.fromstring(file, np.uint8)
    img = cv2.imdecode(npimg,cv2.IMREAD_COLOR)
    img = cv2.rectangle(img, start_point, end_point, color, thickness)
    img = Image.fromarray(img.astype("uint8"))
    rawBytes = io.BytesIO()
    img.save(rawBytes, "png")
    rawBytes.seek(0)
    img_base64 = base64.b64encode(rawBytes.read())
    return jsonify({'status':str(img_base64)})


if __name__ == '__main__':
    app.run(debug = True)

在这里,您将返回base64编码的图像,并在图像上绘制矩形.您可以在下面的图片中看到添加的红色矩形

Here, you return the base64 encoded image with the rectangle drawn on the image. You can see red rectangle added in the below image

这篇关于基于Flask的API可以返回文件吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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