2

I am getting image data in the form of buffer(bytes), but I want to convert it into a base64 string. The data is received inside a JSONArray, like so

JSONArray : `[53,57,51,47,53,57,51,55,50,98,98,54,53,51,54,97,102,101,53,101,102,54,57,54,53,54,53,51,102,98,53,99,98,98,99,51,98,48,52,57,56,52,52,101,54,48,50,99,56,55,101,54,53,97,51,102,56,49,56,57,56,98,102,56,49,57,97,57]`

For that I am copying the JSONArray into "byte" array, like so :

JSONArray bytearray_json = record.getJSONObject("image").getJSONArray("data");
byte[] bytes = new byte[bytearray_json.length()];
for (int i =0; i < bytearray_json.length(); i++ ) {
    bytes[i] = (byte)bytearray_json.get(i);
}
String base_64 = Base64.encodeToString(bytes,Base64.DEFAULT);

But I get an exception : Cannot cast Integer to byte I cannot do bytearray_json.get(i).toString().getBytes(); since it returns a Byte Array.

How can I solve this?

ashwin mahajan
  • 1,654
  • 5
  • 27
  • 50

2 Answers2

5

You can try this out to,

JSONArray jsonArray = response.getJSONObject("image").getJSONArray("data");
byte[] bytes = new byte[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
        bytes[i]=(byte)(((int)jsonArray.get(i)) & 0xFF);
}
 Base64.encodeToString(bytes, Base64.DEFAULT);
Hasangi
  • 280
  • 7
  • 17
  • would you like to elaborate why it needs `& 0xFF` ? – Yusril Maulidan Raji Nov 27 '18 at 09:41
  • Well, there are mainly two reasons to use this `& 0xFF`, 1. To mask the value to get only last 8 bits, and ignores all the rest of the bits. 2. In this case, we are trying to deal with RGB values which is exactly 8 bits long. You can read more [on](https://stackoverflow.com/questions/11380062/what-does-value-0xff-do-in-java) – Hasangi Dec 05 '18 at 06:52
0

Thanks @Hasangi for your answer.

For those of you who wants to use a more modern answer, based on Kotlin:

fun JSONArray.toByteArray(): ByteArray {
    val byteArr = ByteArray(length())
    for (i in 0 until length()) {
        byteArr[i] = (get(i) as Int and 0xFF).toByte()
    }
    return byteArr
}

and to use:

val bytes = jsonObj.getJSONArray("bytes").toByteArray()
Oz Shabat
  • 1,434
  • 17
  • 16