Flask return 图像对象

Flask return image object

我有一个 React Native 项目,我在其中将照片发送到我的 Flask 后端以进行一些图像处理,然后 return 处理后的图像返回到 React Native(对此使用 POST 请求整个过程)。

我能够将图像接收到我的 Flask 应用程序中,并且能够 运行 处理,但是,我不知道如何将图像发送回 React Native。到目前为止,我已经尝试了所有方法,但没有将图像存储在任何地方,但我开始怀疑我是否应该在 flask 中创建一个临时图像文件(利弊是什么)?

这是我目前的情况:

app.py(烧瓶)

@app.route('/analyze-img', methods=['POST'])
def analyze_img():
    # read image file
    filestr = request.files['FrontProfile'].read()
    npimg = np.frombuffer(filestr, dtype=np.uint8)
    img = cv.imdecode(npimg, cv.IMREAD_UNCHANGED)

    # process image
    img_annotated = process_img(img)

    # return output image
    retval, buffer = cv.imencode('.jpg', img_annotated)
    response = make_response(buffer.tobytes())
    return response

但是,由于某种原因,return在响应中未定义(我检查过进入 Flask 的数据是否正常):

const photo = { uri: frontProfile, type: "image/jpeg", name: "photo.jpg" };
var form = new FormData();
form.append("FrontProfile", photo);

await fetch("http://<my IP>:5000/analyze-img", {
  method: "POST",
  body: form,
})
  .then((resp) => resp.json())
  .then((json) => console.log(json))
  .catch((err) => console.error(err));

which returns JSON Parse error: Unexpected identifier "undefined" 非常感谢任何帮助!

问题似乎在:response = make_response(buffer.tobytes()) 行。根据 make_response 文档,

make_response(rv) Convert the return value from a view function to an instance of response_class.

Parameters rv –

the return value from the view function. The view function must return a response. Returning None, or the view ending without returning, is not allowed. The following types are allowed for view_rv:

str (unicode in Python 2) A response object is created with the string encoded to UTF-8 as the body.

bytes (str in Python 2) A response object is created with the bytes as the body.

dict A dictionary that will be jsonify’d before being returned.

由于您将字节对象传递给此方法,因此 make_response 不会隐式转换为您在客户端期望的 JSON 格式。这可以通过使用来解决:response = make_response({"payload": buffer.tobytes()}, 200)