3

I have a ByteBuffer, and I need to add its content to a POST request in order to remotely display the image which represents; but I can't figure it out how to do it.

Doing this doesn't work:

byteBuffer.array()

I have tried to convert it to an array of bytes, but it didn't work because the image wasn't showing properly:

byte[] byteArray = new byte[byteBuffer.remaining()];
frame.duplicate().get(byteArray);
HttpResponse response = null;
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
post.setEntity(new ByteArrayEntity(byteArray));

Also I've think about converting it to an image and get its array of bytes but I don't know how to do it and if it would work...

Any help will be appreciate.

8
  • 1
    byteBuffer.array() doesn't work? That's quite a claim. Commented Mar 9, 2015 at 10:51
  • No, byteBuffer.array() does not form the image correctly, and if I debug the app the result of doing so is an array in which each element is a 0 value... Commented Mar 9, 2015 at 10:53
  • Then either you haven't read anything into it or you haven't debugged cirrextly. Commented Mar 9, 2015 at 10:55
  • @svprdga Show us how you populate the byte buffer. Chances are, the error is there. Commented Mar 9, 2015 at 10:55
  • 1
    @EJP: From the documentation of ByteBuffer.array(): "Returns the byte array which this buffer is based on, if there is one", maybe my ByteBuffer has been made in some other way....?? Commented Mar 9, 2015 at 11:07

2 Answers 2

6
private static byte[] getByteArrayFromByteBuffer(ByteBuffer byteBuffer) {
    byte[] bytesArray = new byte[byteBuffer.remaining()];
    byteBuffer.get(bytesArray, 0, bytesArray.length);
    return bytesArray;
}
Sign up to request clarification or add additional context in comments.

Comments

3

A ByteBuffer created with allocate (not necessarily allocateDirect) should have a backing array, check with hasArray() / isDirect().

byteBuffer.flip();  // Sets limit to current write position.
int n = byteBuffer.limit();
byteBuffer.rewind(); // Already done by flip I think.
byte[] data = new byte[n];
byteBuffer.get(data);

1 Comment

hasArray() returns false. I have tried your code, byteBuffer.limit() returns 0 and the final data array has 0 lenght...

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.