How do I return an image in fastAPI?

前端 未结 6 1915
灰色年华
灰色年华 2020-12-14 17:51

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=[         


        
6条回答
  •  鱼传尺愫
    2020-12-14 18:53

    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")
    

提交回复
热议问题