简体   繁体   中英

Converting array of int to Bitmap on Android

I have an MxN array of ints representing colors (say RGBA format, but that is easily changeable). I would like to convert them to an MxN Bitmap or something else (such as an OpenGL texture) that I can render to the screen. Is there a fast way to do this? Looping through the array and drawing them to the canvas is far too slow.

Try this, it will give you the bitmap:

 // You are using RGBA that's why Config is ARGB.8888 
    bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
 // vector is your int[] of ARGB 
    bitmap.copyPixelsFromBuffer(IntBuffer.wrap(vector));

Or you can generate IntBuffer from the following native method:

private IntBuffer makeBuffer(int[] src, int n) {
    IntBuffer dst = IntBuffer.allocate(n*n);
    for (int i = 0; i < n; i++) {
        dst.put(src[i]);
    }
    dst.rewind();
    return dst;
}

Why not use Bitmap.setPixel ? It's even API level 1:

int[] array  = your array of pixels here...
int   width  = width of "array"...
int   height = height of "array"...

// Create bitmap
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

// Set the pixels
bitmap.setPixels(array, 0, width, 0, 0, width, height);

You can play with offset/stride/x/y as needed.
No loops. No additional allocations.

Yeah, sounds like you have all the info you need. If M is the width and N is the height, you can create a new bitmap with Bitmap.createBitmap, and you can fill in the ARGB values with the setPixels method which takes an int array.

Bitmap.createBitmap

Bitmap.setPixels

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM