Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The use of getPixels() of Android's Bitmap class and how to use it

I'm trying to do some image processing in Android. I need to get a chunk of pixel information of a bitmap. So I tried to use one of the Bitmap class method getPixels(). However, it seems like I'm not using it correctly or I misunderstood of the sole purpose of the method's behaviour.

For example, I'm doing the following in order to get pixel information of a 10 by 10 region of a bitmap from an arbitrary location(bitmap coordinate) x, y.

Bitmap bitmap = BitmapFactory.decodeFile(filePath);
int[] pixels = new int[100];
bitmap.getPixels(pixels, 0, bitmap.getWidth(), x, y, 10, 10);

And I'm getting ArrayIndexOutOfBoundsException. I've been Googling around to see what I'm doing wrong, but I'm clueless. Most of the examples or questions regarding the use of getPixels() are usually for the case of extracting pixel information of the entire image. Hence the size of the int array is usually bitmap.getWidth()*bitmap.getHeight(), x and y values are 0, 0, and the width, height is bitmap's width and height.

Is Bitmap's getPixels() not designed for the purpose of my use(getting a chunk of pixel information of a sub-region of the bitmap)? Or am I using it incorrectly? Is there an alternative way to do this, perhaps using a different class?

I would appreciate it if anyone has something to say about this. Thanks.

like image 356
YoonSoo Lee Avatar asked Nov 18 '12 20:11

YoonSoo Lee


1 Answers

getPixels() returns the complete int[] array of the source bitmap, so has to be initialized with the same length as the source bitmap's height x width.

Using like so, bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, 10, 10); does actually grab the desired pixels from the bitmap, and fills the rest of the array with 0. So with a 10 x 10 subset of a bitmap of 100 x 10, starting at 0,0 the first 100 values would be the desired int value, the rest would be 0.

You could always try using Bitmap.createBitmap() to create your subset bitmap, then use getPixels() on your new Bitmap to grab the complete array.

like image 56
the.Doc Avatar answered Sep 27 '22 23:09

the.Doc