Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.4k points)

  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?

2 Answers

0 votes
by (46k points)

Go for this:

Bitmap bmp = intent.getExtras().get("data");

ByteArrayOutputStream stream = new ByteArrayOutputStream();

bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);

byte[] byteArray = stream.toByteArray();

bmp.recycle();

0 votes
by (2.8k points)

ByteBuffer way of converting Java bitmap to byte array
int size = bitmap.getRowBytes() * bitmap.getHeight();
ByteBuffer byteBuffer = ByteBuffer.allocate(size);
bitmap.copyPixelsToBuffer(byteBuffer);
byte[] byteArray = byteBuffer.array();
// Save and later load these:
int width = bitmap.getWidth();
int height = bitmap.getHeight();
String format = bitmap.getConfig().name();

Byte-array to Bitmap
Bitmap.Config configBmp = Bitmap.Config.valueOf(format);
Bitmap bitmap_tmp = Bitmap.createBitmap(width, height, configBmp);
ByteBuffer buffer = ByteBuffer.wrap(byteArray);
bitmap_tmp.copyPixelsFromBuffer(buffer);

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Oct 17, 2019 in Java by Shubham (3.9k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...