Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently read a Bitmap object into a two-dimensional integer array?

I need to read the entirety of a Bitmap object into a 2-dimensional integer array in my Android application.

Currently, I am reading each pixel individually, one at a time, like so:

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 really long time on large images (about 15 seconds).

Is there a way to do it all in one fell swoop for better efficiency?

like image 862
You'reAGitForNotUsingGit Avatar asked Apr 14 '17 21:04

You'reAGitForNotUsingGit


1 Answers

I'm not familiar with Android dev, but typically for image objects you're able to just grab a reference or copy of some underlying buffer. This buffer is usually 1D, but you should be able to covert it fairly easily. In your case, for grabbing the pixels, there's a function getPixels 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's pixels

FYI, you can index into this type of 1D array using 2D indices:

int pixel = coverImageIntArray1D[x + y*coverImageWidth]

Which will give you the pixel at [x][y]. So you can still use it in a 2D manner without performing an inefficient transformation.

like image 184
Wacov Avatar answered Oct 16 '22 21:10

Wacov