0

I am trying to display an image using <Image/> from react-native. The endpoint is built with Spring and writes the image content to output stream. The endpoint receives the image ID.

If I execute the request from Postman, in the result I can see the image.

I wondered looking for solutions and I think this one is the closest I managed to get https://stackoverflow.com/a/44058739/869793

I saw in the docs that it may work by having the response encoded with base64 but I didn't get there yet and I hope I can make it work without that.

 useEffect(() => {
    axios.get(
      'http://localhost/images/id15', 
      {responseType: 'arraybuffer'}
    )
    .then(resp => {
      const data = Buffer.from(resp.data, 'binary').toString('base64')
      console.log("resp => " + data);
      let imageUri = "data:image/jpeg;base64," + data;
      setSource({uri: imageUri})
    })
  }, []) 


<Image
  style={styles.tinyLogo}
  source={source}
/>

Outputs I get in the log by mixing in different params. Nothing displayed the image.

 LOG  resp => ����
 LOG  resp => 77+977+977+977+9
 LOG  resp => /f39/Q==
tzortzik
  • 4,993
  • 9
  • 57
  • 88

1 Answers1

0

I ended up creating an endpoint that is retrieving the encoded image.

Spring code:

@GetMapping("/encoded-base64/{id}")
public Map<String, String> retrieveBase64EncodedImage(@PathVariable UUID id) {
    return singletonMap("data", imageService.findByIdAndEncode(id));
}

public String findByIdAndEncode(UUID id) {
    Image image = imageRepository.findById(id).orElseThrow();
    InputStream inputStream = storageService.get(image.getFilePath());
    try {
        byte[] bytes = FileCopyUtils.copyToByteArray(inputStream);
        return Base64.getEncoder().encodeToString(bytes);
    } catch (IOException e) {
        throw new RuntimeException("Cannot copy stream", e);
    }
}

React Native code:

  useEffect(() => {
    axios.getAsync(
      'path_to_server/encoded-base64/37d1302d-3ba2-4b4e-b08d-5323979abf38', 
    )
    .then(resp => {
      const data = resp.data.data
      console.log("resp => " + JSON.stringify(data));
      let imageUri = "data:image/jpeg;base64," + data;
      setSource({uri: imageUri})
    }) 
  }, []) 


  <Image
    style={styles.tinyLogo}
    source={source}
  />
tzortzik
  • 4,993
  • 9
  • 57
  • 88