return numpy 数组作为来自 fastapi 的图像

return numpy array as image from fastapi

我用 img = imageio.imread('hello.jpg') 加载图像。 我想 return 这个 numpy 数组作为图像。我知道我可以做到 return FileResponse('hello.jpg')。但是以后我会将图片作为numpy数组。

我如何 return 来自 fastapi 的 numpy 数组 img 等同于 return FileResponse('hello.jpg')

例如,您可以使用 StreamingResponse (https://fastapi.tiangolo.com/advanced/custom-response/#using-streamingresponse-with-file-like-objects) 来执行此操作,但在此之前,您需要将 numpy 数组转换为 io.BytesIOio.StringIO

您不应该使用 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 . 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,以便在浏览器中查看图像。下面的示例:

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