0

so I'm returning a processed image from a backed server that was developed in fastapi this function returns an image.

@app.post("/object-to-img")
async def detect_return_base64_img(file:bytes = File(...) ):
    input_image = get_image_from_bytes(file)
    results = model(input_image)
    results.render()  # updates results.imgs with boxes and labels
    for img in results.imgs:
        bytes_io = io.BytesIO()
        img_base64 = Image.fromarray(img)
        img_base64.save(bytes_io, format="jpeg")

    return Response(content=bytes_io.getvalue(), media_type="image/jpeg")

To be clear i get responses in this form.

{
    "data": "����\u0000\u0010JFIF\u0000\u0001\u0001\u0000\u0000\u0001\u0000\u0001\u0000\u0000��\u0000C\u0000\b\u0006\u0006\u0007\u0006\u0005\b\u0007\u0007\u0007\t\t\b\n\f\u0014\r\f\u000b\u000b\f\u0019\u0012\u0013\u000f\u0014\u001d\u001a\u001f\u001e\u001d\u001a\u001c\u001c $.' \",#\u001c\u001c(7),01444\u001f'9=82<.342��\u0000C\u0001\t\t\t\f\u000b\f\u0018\r\r\u00182!\u00��[cFYK\u001erz��Tcf);��b�\u0004�\u0001��W���\u0014%\u0003�?)�O�M[Yc�/�\u0019A\u0019�\u0000���=2k�\u0013P�\r\u0013�l\u0014�߇P}3ץU�\u0012e-��`��.�\u001bz�\u001e\r/\u0006��`%�\b�ϭUHdk�<yt�(�<��j[_0^�L���du�6�\t>嗷s!d#\f0�ߦ?ϭV�|��VVfLpp\u0006Z�ц�\nY\u0011��\fy�z�}�l\u0013�t�Y��zg�\u0011A\"�\u001d���-��ZM߹�r�\u0011��Lf�[���b]�%��A!��3\u0011�@\u0019�=\u0005\\��ɼ�1r�݆G\u001fʛZ\t=H~���F$?*",
    "status": 200,
    "statusText": "OK",
    "headers": {
        "content-length": "46335",
        "content-type": "image/jpeg"
    },
    "config": {
        "url": "object-to-img/",
        "method": "post",
        "data": {},
        "headers": {
            "Accept": "application/json, text/plain, */*"
        },
        "baseURL": "http://localhost:8000/",
        "transformRequest": [
            null
        ],
        "transformResponse": [
            null
        ],
        "timeout": 0,
        "xsrfCookieName": "XSRF-TOKEN",
        "xsrfHeaderName": "X-XSRF-TOKEN",
        "maxContentLength": -1,
        "maxBodyLength": -1
    },
    "request": {}
}

now how to convert this data into an image that can be then rendered using image tags react.js? <img src={} alt="" />

i tried converting it into base64 and <img src={URL.createObjectURL(data)} alt="" /> couldn't really get it right.

  • You'll need to wrap it in a `Blob` object if you want to use the raw binary data directly: https://stackoverflow.com/questions/66466412/how-can-i-convert-raw-binary-data-to-a-blob-and-display-it-in-an-img-tag - otherwise, if you return base64, prepend the mime type in front of the base64 string to tell your browser what kind of file type we're talking about (`data:image/jpeg;base64,`) – MatsLindh Mar 28 '22 at 11:44

0 Answers0