Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render a byte[] as Bitmap in Android

Tags:

java

android

I'm getting a byte array from a JNI call, and trying to construct a Bitmap object with it.

My problem is, the following code, returns null.

    byte[] image = services.getImageBuffer(1024, 600);
    Bitmap bmp = BitmapFactory.decodeByteArray(image, 0, image.length);

Any tips about it?

PS: The pixel layout is BGR, not a RGB.

like image 531
Marcos Vasconcelos Avatar asked Jan 13 '11 18:01

Marcos Vasconcelos


2 Answers

The doc says the method returns "null if the image could not be decode." You can try:

byte[] image = services.getImageBuffer(1024, 600);
InputStream is = new ByteArrayInputStream(image);
Bitmap bmp = BitmapFactory.decodeStream(is);

Even if I don't think it's going to change anything though.. Try to have a look at android.graphics.BitmapFactory.Options as well

like image 168
CodegistCRest Avatar answered Nov 19 '22 12:11

CodegistCRest


The decodeByteArray really doens't works with this format. I change from BGR to RGB manually.

    byte[] image = services.getImageBuffer(1024, 600);

    Bitmap bmp = Bitmap.createBitmap(1024, 600, Bitmap.Config.RGB_565);
    int row = 0, col = 0;
    for (int i = 0; i < image.length; i += 3) {
        bmp.setPixel(col++, row, image[i + 2] & image[i + 1] & image[i]);

        if (col == 1024) {
            col = 0;
            row++;
        }

However,

for (i < image.length) 。。。bmp.setPixel(image[i + 2] & image[i + 1] & image[i]); 

can cause:

08-29 14:34:23.460: ERROR/AndroidRuntime(8638): java.lang.ArrayIndexOutOfBoundsException

like image 40
Marcos Vasconcelos Avatar answered Nov 19 '22 12:11

Marcos Vasconcelos