如何在 fastAPI 中返回图像? [英] How do I return an image in fastAPI?

查看:159
本文介绍了如何在 fastAPI 中返回图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 python 模块 fastAPI,我不知道如何返回图像.在烧瓶中,我会做这样的事情:

Using the python module fastAPI, I can't figure out how to return an image. In flask I would do something like this:

@app.route("/vector_image", methods=["POST"])
def image_endpoint():
    # img = ... # Create the image here
    return Response(img, mimetype="image/png")

这个模块对应的调用是什么?

what's the corresponding call in this module?

推荐答案

我遇到了类似的问题,但使用的是 cv2 图像.这可能对其他人有用.使用 StreamingResponse.

I had a similar issue but with a cv2 image. This may be useful for others. Uses the StreamingResponse.

import io
from starlette.responses import StreamingResponse

app = FastAPI()

@app.post("/vector_image")
def image_endpoint(*, vector):
    # Returns a cv2 image array from the document vector
    cv2img = my_function(vector)
    res, im_png = cv2.imencode(".png", cv2img)
    return StreamingResponse(io.BytesIO(im_png.tobytes()), media_type="image/png")

这篇关于如何在 fastAPI 中返回图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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