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}
/>

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

I have already tested with base64 and its working. Just that I need to serve byte-array image due to the large size of base64
Can you not convert the byte[] to base64 in react somehow?
1

You can use this:

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

<Image style = {styles.image} source = {{uri: getImageSource()}}/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.