You shouldn't be using StreamingResponse, as suggested by some other answer. If the numpy array is fully loaded into memory from the beginning, StreamingResponse does not make sense at all. Please have a look at this answer. You should instead use Response, by passing the image bytes (after writing to BytesIO buffered stream, as described in the documentation) defining the media_type, as well as setting the Content-Disposition header, as described here, so that the image is viewed in the browser. Example below:
import io
import imageio
from imageio import v3 as iio
from fastapi import Response
@app.get("/image", response_class=Response)
def get_image():
im = imageio.imread("test.jpeg") # 'im' could be an in-memory image (numpy array) instead
with io.BytesIO() as buf:
iio.imwrite(buf, im, plugin="pillow", format="JPEG")
im_bytes = buf.getvalue()
headers = {'Content-Disposition': 'inline; filename="test.jpeg"'}
return Response(im_bytes, headers=headers, media_type='image/jpeg')