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

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.


Most guys want to use getPixels() getting a specific region pixels, but actually it returned a full size of the origin bitmap. Valid region is placed left corner and others are translucent colors. I suggest you use Android Studio debug mode to see the visual pixels by creating a bitmap.

And the following is my version of getPixels() to get specific region pixels:

public class BitmapHelper {

public static int[] getBitmapPixels(Bitmap bitmap, int x, int y, int width, int height) {
    int[] pixels = new int[bitmap.getWidth() * bitmap.getHeight()];
    bitmap.getPixels(pixels, 0, bitmap.getWidth(), x, y,
            width, height);
    final int[] subsetPixels = new int[width * height];
    for (int row = 0; row < height; row++) {
        System.arraycopy(pixels, (row * bitmap.getWidth()),
                subsetPixels, row * width, width);
    }
    return subsetPixels;
}
}