简体   繁体   English

如何使用 FastAPI 将 numpy 数组作为图像返回?

[英]How to return a numpy array as an image using FastAPI?

I load an image with img = imageio.imread('hello.jpg') .我用img = imageio.imread('hello.jpg')加载图像。 I want to return this numpy array as an image.我想将此 numpy 数组作为图像返回。 I know I can do return FileResponse('hello.jpg') , however, in the future, I will have the pictures as numpy arrays.我知道我可以return FileResponse('hello.jpg') ,但是,在未来,我将拥有 numpy arrays 的图片。

How can I return the numpy array img from FastAPI server in a way that it is equivalent to return FileResponse('hello.jpg') ?如何以等效于return FileResponse('hello.jpg')的方式从 FastAPI 服务器返回 numpy 数组img

You shouldn't be using StreamingResponse , as suggested by some other answer.正如其他答案所建议的那样,您不应该使用StreamingResponse If the numpy array is fully loaded into memory from the beginning, StreamingResponse does not make sense at all.如果从一开始就将 numpy 数组完全加载到 memory 中,则StreamingResponse根本没有意义。 Please have a look at this answer .请看一下这个答案 You should instead useResponse , 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.您应该使用Response ,通过传递图像字节(在写入BytesIO缓冲 stream 后,如文档中所述)定义media_type ,以及设置Content-Disposition header ,如此处所述,以便在浏览器。 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')

You can use StreamingResponse ( https://fastapi.tiangolo.com/advanced/custom-response/#using-streamingresponse-with-file-like-objects ) to do it eg, but before you will need to convert your numpy array to the io.BytesIO or io.StringIO您可以使用 StreamingResponse ( https://fastapi.tiangolo.com/advanced/custom-response/#using-streamingresponse-with-file-like-objects ) 来执行此操作,但在您需要将 numpy 数组转换为之前io.BytesIOio.StringIO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM