5

I'm posting an image, and getting the processed image as a response from the backend. The problem is with the response part. I can't display the image whatever I do.

First of all, Postman works. So the backend is fine, I'm seeing the image response in postman. Just in any case, this is the related part of the FastAPI backend:

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")

I have tried axios and fetch both.

Axios' response looks like this with the headers: (I'm getting 200)

"data": "����",
  "headers": Object {
    "content-length": "86387",
    "content-type": "image/jpeg",
    "date": "Thu, 05 May 2022 17:45:03 GMT",
    "server": "uvicorn",
  },

Data looks weird as you can see.

This is the code:

axios.post("http://10.0.0.3:8000/object-to-img", body, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then(function (response) {
          setImage("data:image/jpeg;base64," + response.data);
        })
        .catch(function (error) {
          console.log(error);
        });

And this is how I try to visualize it:

<Image
        style={{
          flex: 1,
          width: 500,
          height: 500,
          resizeMode: "contain",
        }}
        source={{ uri: image }}
      />

React Native's .fetch() method simply cannot even parse the thing. JSON Parse error: Unrecognized token '�'

Whatever I do, I cannot display the image.

Aras Uludağ
  • 113
  • 2
  • 7
  • Please have a look at the answers [here](https://stackoverflow.com/a/71639658/17865804) and [here](https://stackoverflow.com/a/71324775/17865804). – Chris May 05 '22 at 18:43

1 Answers1

0

You can use fetchBlob instead of axios to fetch Images from an API which return only encoded IMAGE

    RNFetchBlob.fetch("GET", obj.url, {
    "content-type": "image/jpeg",
    Authorization: `Bearer ${obj.token}`,
  })
    .then((res) => {
     console.log(res);
    })
    .catch((errorMessage, statusCode) => {
      console.log("errorMessageFETCH", errorMessage);
    });
Zach Jensz
  • 3,650
  • 5
  • 15
  • 30