Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New Bitmap Changed on Copy Using Buffer

When I am using copyPixelsFromBuffer and copyPixelsToBuffer, the bitmap is not displaying as the same one, I have tried below code:

Bitmap bm = BitmapFactory.decodeByteArray(a, 0, a.length);
int[] pixels = new int[bm.getWidth() * bm.getHeight()];
bm.getPixels(pixels, 0, bm.getWidth(), 0, 0,bm.getWidth(),bm.getHeight());

ByteBuffer buffer = ByteBuffer.allocate(bm.getRowBytes()*bm.getHeight());
bm.copyPixelsToBuffer(buffer);//I copy the pixels from Bitmap bm to the buffer

ByteBuffer buffer1 = ByteBuffer.wrap(buffer.array());
newbm = Bitmap.createBitmap(160, 160,Config.RGB_565);
newbm.copyPixelsFromBuffer(buffer1);//I read pixels from the Buffer and put the pixels     to the Bitmap newbm.

imageview1.setImageBitmap(newbm);
imageview2.setImageBitmap(bm);

Why the Bitmap bm and newbm did not display the same content?

like image 987
Hexor Avatar asked Apr 01 '12 11:04

Hexor


1 Answers

In your code, you are copying the pixels into a bitmap with RGB_565 format, whereas the original bitmap from which you got the pixels must be in a different format.

The problem is clear from the documentation of copyPixelsFromBuffer():

The data in the buffer is not changed in any way (unlike setPixels(), which converts from unpremultipled 32bit to whatever the bitmap's native format is.

So either use the same bitmap format, or use setPixels() or draw the original bitmap onto the new one using a Canvas.drawBitmap() call.

Also use bm.getWidth() & bm.getHeight() to specify the size of the new bitmap instead of hard-coding as 160.

like image 93
Dheeraj Vepakomma Avatar answered Oct 09 '22 23:10

Dheeraj Vepakomma