I'm using Bitmap.getPixels with the code below to get a row of 1 pixel height in the middle of a bitmap image:
int width = source.getWidth();
int height = source.getHeight();
int[] horizontalMiddleArray = new int[width];
source.getPixels(horizontalMiddleArray, 0, width, 0, height / 2, width, 1);
The result is something like:
Now I want to do the same, but in the vertical:
I tried the same logic, but it's not working and I don't see what I'm doing wrong:
int[] verticalMiddleArray = new int[height];
source.getPixels(verticalMiddleArray, 0, width, width / 2, 0, 1, height -1 );
With this code I receive a ArrayIndexOutOfBoundsException
exception.
The size of the bitmap for now is 32x32.
The documentation for that method is either just plain wrong, or unintentionally misleading, depending on interpretation. For the stride
parameter, it states:
stride
int
: The number of entries in pixels[] to skip between rows (must be >= bitmap's width). Can be negative.
Here, "bitmap's width" does not mean the source's width, but the destination's. You're getting that ArrayIndexOutOfBoundsException
when it does the check to ensure the provided array is big enough for the requested data. Since your source bitmap is wider than the destination, the size needed for the data is therefore greater than the size of the array you passed.
The call for the vertical slice should be:
source.getPixels(verticalMiddleArray, 0, 1, width / 2, 0, 1, height);
(I'm assuming you had height - 1
there as an attempted fix.)