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?
When you create a FastAPI path operation you can normally return any data from it: a dict , a list , a Pydantic model, a database model, etc. By default, FastAPI would automatically convert that return value to JSON using the jsonable_encoder explained in JSON Compatible Encoder.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With