Bitmap bmp = intent.getExtras().get("data");
int size = bmp.getRowBytes() * bmp.getHeight();
ByteBuffer b = ByteBuffer.allocate(size);
bmp.copyPixelsToBuffer(b);
byte[] bytes = new byte[size];
try {
b.get(bytes, 0, bytes.length);
} catch (BufferUnderflowException e) {
// always happens
}
// do something with byte[]
When I look at the buffer after the call to copyPixelsToBuffer
the bytes are all 0... The bitmap returned from the camera is immutable... but that shouldn't matter since it's doing a copy.
What could be wrong with this code?
Here is bitmap extension
.convertToByteArray
wrote in Kotlin.Your byte array is too small. Each pixel takes up 4 bytes, not just 1, so multiply your size * 4 so that the array is big enough.
Ted Hopp is correct, from the API Documentation :
"... After this method returns, the current position of the buffer is updated: the position is incremented by the number of elements written in the buffer. "
and
"Reads bytes from the current position into the specified byte array, starting at the specified offset, and increases the position by the number of bytes read."
Use below functions to encode bitmap into byte[] and vice versa
Do you need to rewind the buffer, perhaps?
Also, this might happen if the stride (in bytes) of the bitmap is greater than the row length in pixels * bytes/pixel. Make the length of bytes b.remaining() instead of size.
CompressFormat is too slow...
Try ByteBuffer.
※※※Bitmap to byte※※※
※※※byte to bitmap※※※