简体   繁体   English

如何在 fastapi 的一个响应中返回图像和 json?

[英]How to return image and json in one response in fastapi?

I get an image, change it, then it is classified using a neural network, should return a new image and json with a response.我得到一张图像,对其进行更改,然后使用神经网络对其进行分类,应该返回一个新图像和 json 并返回一个响应。 How to do it with one endpoint?如何使用一个端点来做到这一点? image is returned with Streaming Response but how to add json to it?图像与流响应一起返回,但如何将 json 添加到它?

import io
from starlette.responses import StreamingResponse

app = FastAPI()

@app.post("/predict")
def predict(file: UploadFile = File(...)):
    img = file.read()
    new_image = prepare_image(img)
    result = predict(new_image)
    return StreamingResponse(io.BytesIO(new_image.tobytes()), media_type="image/png")

I added json to response headers.我将 json 添加到响应标头中。 change from:更改自:

@app.post("/predict")
def predict(file: UploadFile = File(...)):
    img = file.read()
    new_image = prepare_image(img)
    result = predict(new_image)
    return StreamingResponse(io.BytesIO(new_image.tobytes()), media_type="image/png")

to

@app.post("/predict/")
def predict(file: UploadFile = File(...)):
    file_bytes = file.file.read()
    image = Image.open(io.BytesIO(file_bytes))
    new_image = prepare_image(image)
    result = predict(image)
    bytes_image = io.BytesIO()
    new_image.save(bytes_image, format='PNG')
    return Response(content = bytes_image.getvalue(), headers = result, media_type="image/png")

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

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