I'm trying to send image as bytes because bandwidth is being killed by base64 strings. I've seen examples about transferring it as stream https://stackoverflow.com/a/17573179/8359785 but the problem is that I'm not sure how to transfer json data with it at the same http request
Asked
Active
Viewed 2,302 times
0
-
Add a field in the `JSON` to accommodate the **image** `Bytes`. – Saif Ahmad Jan 09 '18 at 12:16
-
How to do that when json can't handle binary data ,_, or am i missing something here? – Waseem Jan 09 '18 at 12:20
-
Add your image `Byte[]` in the `JSON` – Saif Ahmad Jan 09 '18 at 12:23
-
Use multipart? One part for the Json and one part for the image. I would try and provide some useful information/example code but I don't know what libraries you're using, etc. – BeUndead Jan 09 '18 at 12:46
2 Answers
1
You could add a field in the JSON
to accommodate the Byte[]
of your Image
.
JSON
could be like this:
{
...,
"Image": [83, 97, 105, 102, 32, 115, 97, 121, 115, 32, 104, 101, 108, 108, 111],//Byte array of your image
...
}

Saif Ahmad
- 1,118
- 1
- 8
- 24
-
That actually worked, didn't expect it to. Thanks a lot! I'll also try other solutions though to see which saves as much bandwidth as possible. – Waseem Jan 09 '18 at 13:05
-
After testing the difference, this appears to use double the amount of bandwidth than when transferring base64.. But still, good to know that bytes can be included in json – Waseem Jan 09 '18 at 13:37
-
I gave answer for **How to accommodate Byte in JSON** if you want to save bandwidth, there is a better of doing it. – Saif Ahmad Jan 09 '18 at 18:18
1
If you need to reduce the bandwidth usage to its maximum, just send data like this :
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
dOut.writeInt(imageBytes.length);
dOut.write(imageBytes);
dOut.writeInt(jsonBytes.length);
dOut.write(jsonBytes);
Receive code:
DataInputStream dIn = new DataInputStream(socket.getInputStream());
int imageBytesLength = dIn.readInt();
byte[] imageBytes= new byte[imageBytesLength];
dIn.readFully(imageBytes, 0, imageBytesLength);
int jsonBytesLength = dIn.readInt();
byte[] jsonBytes= new byte[jsonBytesLength ];
dIn.readFully(jsonBytesLength , 0, jsonBytesLength );

BluEOS
- 576
- 6
- 13