如何在fastAPI中返回图像?

2024-09-19 18:39:16 发布

您现在位置:Python中文网/ 问答频道 /正文

使用python模块fastAPI,我不知道如何返回图像。在烧瓶里我会这样做:

@app.route("/vector_image", methods=["POST"])
def image_endpoint():
    # img = ... # Create the image here
    return Response(img, mimetype="image/png")

这个模块中对应的调用是什么?在


Tags: 模块图像imageappimg烧瓶defcreate
3条回答

我也有类似的问题,但有一个cv2的图像。这可能对其他人有用。使用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")

来自@SebastiánRamírez的answer为我指出了正确的方向,但是对于那些想要解决问题的人来说,我需要几行代码才能使其工作。我需要从starlette导入FileResponse(不是fastAPI?),添加CORS支持,并从临时文件返回。也许还有更好的方法,但我无法让流媒体工作:

from starlette.responses import FileResponse
from starlette.middleware.cors import CORSMiddleware
import tempfile

app = FastAPI()
app.add_middleware(
    CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]
)

@app.post("/vector_image")
def image_endpoint(*, vector):
    # Returns a raw PNG from the document vector (define here)
    img = my_function(vector)

    with tempfile.NamedTemporaryFile(mode="w+b", suffix=".png", delete=False) as FOUT:
        FOUT.write(img)
        return FileResponse(FOUT.name, media_type="image/png")

它还没有被正确地记录,但是你可以使用Starlette中的任何东西。在

所以,如果磁盘中的文件路径是https://www.starlette.io/responses/#fileresponse,那么可以使用FileResponse

如果它是在您的路径操作中创建的类似文件的对象,那么在Starlette的下一个稳定版本(由FastAPI内部使用)中,您还可以在StreamingResponse中返回它。在

相关问题 更多 >