Ad

Byte Array Of Image Gets Stored As String, How To Get It Back To Byte Array

- 1 answer

I'm using android as my front end and Spring with Hibernate as my back-end. I send a byte array of my image to get stored in this entity:

public class ApplicationUser {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Lob
    @Column(name = "image_bytes", columnDefinition="BLOB")
    private byte[] imageBytes;
}

However, in the H2 console i can see it gets stored as a String, hundreds of characters, so i quess the byte array was in some way converted to a string. So my questions:

  • Why is this happening ? Why does it get stored as a String? Why not store the byte array as it is ?
  • If it has to get stored as a String, then how can i decode it back to the right byte array? If i take the string, and do a myStringThatGotReturned.getBytes(), i get a diffrent byte array ( so basicly i dont get the right image back). I quess im not decoding it in the right way. Any way i can figure out how to decode that string back to the byte array i sent to the back-end ?
Ad

Answer

It is a JSON conversion problem. As JSON is a text format, binary data like those bytes often are converted to Base64 using digits, capitals, small letters and two symbols +/ = 64 "digits" each representing 6 bits.

So probably the handling by the JSON library already works. You could convert the String value yourself with

bytes[] b = Base64.getDecoder().decode(str);
Ad
source: stackoverflow.com
Ad