1

I load an image with img = imageio.imread('hello.jpg'). I want to return this numpy array as image. I know I can do return FileResponse('hello.jpg'). But in the future I will have the pictures as numpy arrays.

How can I return the numpy array img from fastapi in a way that it is equivalent to return FileResponse('hello.jpg')?

Skyy2010
  • 686
  • 6
  • 16

2 Answers2

1

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')
Chris
  • 4,940
  • 2
  • 7
  • 28
0

You can use StreamingResponse (https://fastapi.tiangolo.com/advanced/custom-response/#using-streamingresponse-with-file-like-objects) to do it e.g., but before you will need to convert your numpy array to the io.BytesIO or io.StringIO

dukkee
  • 1,107
  • 1
  • 7
  • 17