Android: can't create Bitmap with createBitmap

2019-03-05 05:31发布

问题:

I'm fairly new to programming on the android platform. I'm having some problems massaging an int array to turn it into a Bitmap.

Each element in the int array is a number from 0 to 255, and represents a grey-scale pixel color (so 0 would be black, and 255 would be white, etc...). Here's my code:

int nPixels = 262144;
int width = 512;
int height = 512;
int[] converted = new int[nPixels];
int alpha = 255;
for (int i = 0; i < nPixels; i++) {
    //greyscale, so all r, g, and b have the same value
    converted[i] = (alpha << 24) | (pixels[i] << 16) | (pixels[i] << 8) | pixels[i];
}

Bitmap bm = Bitmap.createBitmap(converted, width, height, Bitmap.Config.ARGB_8888);

The resulting bitmap has height and width of -1, which indicates that the createBitmap function didn't work. What is wrong with my method?

Oh, I took the shifting part for making the color from http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/graphics/CreateBitmap.html.

Edit: thought it might've been because alpha was 256 instead of 255, but I still get the same error.

回答1:

How do you learn that your Bitmap has [-1 -1] size? To get size, use:

int w = bm.getWidth();
int h = bm.getHeight();

This is working fine.



回答2:

I not sure if you can create the bitmap directly from the int array. You may need to iterate through the pixels of the bitmap and set the pixel value from the array using the bitmap setPixel method.

bitmap.setPixel (int x, int y, int color)