1

I am able to view the byte-array image on Swagger but not on React Native. I have tried converting it to base64 and it works but I want to know how to display it in byte-array.

  • This is my backend endpoint, using spring-boot
@GetMapping(value = "/{id}", produces = { "image/jpg", "image/jpeg", "image/png" })
public ResponseEntity<Resource> getImage(@PathVariable final UUID id){
    final User user =  userService.findById(id).orElseThrow(() -> new ResourceNotFoundException("User Not Found."));
    Optional<Image> image = imageService.findByUser(user);
    if(image.isPresent()) {
        byte[] bytes = Files.readAllBytes(Paths.get(image.get().getSignDocPath()));
        return ResponseEntity.ok().body(new ByteArrayResource(bytes));
    }
}
  • And this is how I am displaying the image on React Native
<Image
  source={{ uri: imageItem.url }}
  style={styles.imagePreview}
/>
myeongkil kim
  • 2,465
  • 4
  • 16
  • 22

2 Answers2

1

You can't display byte array in react native better it would be to convert byte array into base64 on backend then use it in React Native like.

How to convert a byte array to Base64 in Java?

Java 8+

Encode or decode byte arrays:

byte[] encoded = Base64.getEncoder().encode("Hello".getBytes());
println(new String(encoded));   // Outputs "SGVsbG8="

byte[] decoded = Base64.getDecoder().decode(encoded);
println(new String(decoded))    // Outputs "Hello"

Or if you just want the strings:

String encoded = Base64.getEncoder().encodeToString("Hello".getBytes());
println(encoded);   // Outputs "SGVsbG8="

String decoded = new String(Base64.getDecoder().decode(encoded.getBytes()));
println(decoded)    // Outputs "Hello"

Java < 8

Base64 codec = new Base64();
byte[] encoded = codec.encode("Hello".getBytes());
println(new String(encoded));   // Outputs "SGVsbG8="

byte[] decoded = codec.decode(encoded);
println(new String(decoded))    // Outputs "Hello"

Or if you just want the strings:

Base64 codec = new Base64();
String encoded = codec.encodeBase64String("Hello".getBytes());
println(encoded);   // Outputs "SGVsbG8="

String decoded = new String(codec.decodeBase64(encoded));
println(decoded)    // Outputs "Hello"

for more information. Follow

Imran Shad
  • 58
  • 13
1

You can use this:

const getImageSource = () => {
    return `data:image/jpeg;base64,${source}`
}

<Image style = {styles.image} source = {{uri: getImageSource()}}/>
janw
  • 8,758
  • 11
  • 40
  • 62