Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting Java bitmap to byte array

  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?

like image 371
Tom Fobear Avatar asked Feb 14 '11 05:02

Tom Fobear


People also ask

How to convert bitmap image to array in Java?

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.

What is a byteArray?

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..

What does bitmap recycle do?

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" .


2 Answers

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(); 
like image 156
Mezm Avatar answered Sep 20 '22 19:09

Mezm


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); 
like image 25
朱西西 Avatar answered Sep 19 '22 19:09

朱西西