How can I efficiently read a Bitmap object into a two dimensional integer array?
I need to read an entire Bitmap object in a 2 dimensional integer array in an android app.
I am currently reading each pixel separately, one at a time, for example:
for (int y = 0; y < coverImageHeight; y++)
{
for (int x = 0; x < coverImageWidth; x++)
{
coverImageIntArray[x][y] = coverImageBitmap.getPixel(x, y);
}
}
However, this takes a very long time on large images (about 15 seconds).
Is there a way to do it all in one fell swoop to improve efficiency?
source to share
I'm not familiar with Android dev, but usually for image objects, you can just get a link or a copy of some underlying buffer. This buffer is usually 1D, but you can hide it quite easily. In your case, there is a getPixels function for grabbing pixels , which looks perfect.
int[] coverImageIntArray1D = new int[coverImageWidth * coverImageHeight]
coverImageBitmap.getPixels(coverImageIntArray1D, 0, coverImageWidth,
0, 0, coverImageWidth, coverImageHeight)
// coverImageIntArray1D should now contain the entire image pixels
FYI, you can index this type of 1D array using 2D indices:
int pixel = coverImageIntArray1D[x + y*coverImageWidth]
Which will give you a pixel in [x][y]
. Thus, you can still use it in 2D mode without performing inefficient conversion.
source to share
I just checked out an old project I was using with OCR and used the method you present in your answer. My images were only 28x28 pixels.
Usage getPixels()
is probably faster.
See void getPixels (int [] pixels, int offset, int stride, int x, int y, int width, int height)
The code might look like
bitmap.getPixels(intArray, 0, bmp.getWidth(), 0, 0, bmp.getWidth(), bmp.getHeight());
This will copy the Color value bitmap into an int array.
source to share
Instead of using a two-dimensional array, consider using a bit of for-loop logic and a one-dimensional array with
void getPixels (int[] pixels,
int offset,
int stride,
int x,
int y,
int width,
int height)
This approach should be much more efficient than trying to split a one-dimensional array into two-dimensional arrays, as you have to convert the pixel data that appears to be internally stored as int[]
, to int[][]
, just to simplify your logic.
int[] pixels = new int[bitmap.getWidth() * bitmap.getHeight()];
bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
for (int row = 0; row < bitmap.getHeight(); row++)
for (int column = 0; column < bitmap.getWidth(); column++)
Color color = Color.valueOf(pixels[row * bitMap.getWidth() + column]);
Take a look at Android developers link for Bitmap.getPixels (int [], int, int, int, int, int, int) and Color.valueOf (int) (to extract individual color components Color.alpha (int) , Color.red ( int) , Color.green (int) and Color.blue (int) respectively.)
source to share