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?
This example demonstrates how do I convert java bitmap to byte array in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
A byte array is simply an area of memory containing a group of contiguous (side by side) bytes, such that it makes sense to talk about them in order: the first byte, the second byte etc..
The recycle() method allows an app to reclaim memory as soon as possible. Caution: You should use recycle() only when you are sure that the bitmap is no longer being used. If you call recycle() and later attempt to draw the bitmap, you will get the error: "Canvas: trying to use a recycled bitmap" .
Try something like this:
Bitmap bmp = intent.getExtras().get("data"); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] byteArray = stream.toByteArray(); bmp.recycle();
CompressFormat is too slow...
Try ByteBuffer.
※※※Bitmap to byte※※※
width = bitmap.getWidth(); height = bitmap.getHeight(); int size = bitmap.getRowBytes() * bitmap.getHeight(); ByteBuffer byteBuffer = ByteBuffer.allocate(size); bitmap.copyPixelsToBuffer(byteBuffer); byteArray = byteBuffer.array();
※※※byte to bitmap※※※
Bitmap.Config configBmp = Bitmap.Config.valueOf(bitmap.getConfig().name()); Bitmap bitmap_tmp = Bitmap.createBitmap(width, height, configBmp); ByteBuffer buffer = ByteBuffer.wrap(byteArray); bitmap_tmp.copyPixelsFromBuffer(buffer);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With