New Bitmap Changed on Copy Using Buffer
Asked Answered
A

1

6

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?

Apery answered 1/4, 2012 at 11:51 Comment(0)
T
1

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.

Tetrasyllable answered 1/4, 2012 at 14:16 Comment(3)
BitmapFactory.Options opts = new Options(); opts.inPreferredConfig = Config.RGB_565; bm = BitmapFactory.decodeByteArray(a, 0, a.length, opts); The original bitmap's config is RGB565, even I do not set the config, the config is default as RGB565...Apery
@Apery Do the other methods described in my answer work? How different does newbm look compared to bm?Tetrasyllable
The size is not right, and the quality is very low. I found a solution myself which like this, create a Bitmap called originBm, and called the BitmapFactory's decode method to initial the originBm(just make sure the parameter could initial the originBm right), then I use newbm = originBm; newbm.copyPixelsFromBuffer(buffer1). After this, the newbm could display the right thing. I don't know which reason cause this, but i thought maybe when using copyPixelsFromBuffer(), we miss something which the createBitmap() method could not give to us.Apery

© 2022 - 2024 — McMap. All rights reserved.