0

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

Waseem
  • 577
  • 2
  • 4
  • 18

2 Answers2

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