Search code examples
androidarraysbitmapcamerapreview

Android Studio Color int array to Color int matrix


I'm using Android Studio 2.2 and I am getting byte[] data array from onPreviewFrame() from the camera. I have a mutable bitmap with the same size as the resolution of the image from the camera. I want to override the pixels of the bitmap with the pixels from the int[] array that I get from converting the byte[] data array from YUV to RGB format. So I do the following:

public static void correctWithIntArray(Bitmap bmp,int[] data) {
    for(int y=0;y<bmp.getHeight();y++) {
        for(int x=0;x<bmp.getWidth();x++) {
            bmp.setPixel(x,y,data[y*bmp.getHeight() + x]);
        }
    }
}

But I get a very strange result in the output.

Here is the image that I made with Android classes to get the image: Original

And here is the image I get when using the correctWithIntArray: CorrectedImage

What am I doing wrong in that loop?

The function for creating the int[] data array in my function is:

/**
 * Converts YUV420 NV21 to RGB8888
 *
 * @param data byte array on YUV420 NV21 format.
 * @param width pixels width
 * @param height pixels height
 * @return a RGB8888 pixels int array. Where each int is a pixels ARGB.
 */
public static int[] convertYUV420_NV21toRGB8888(byte [] data, int width, int height) {
    int size = width*height;
    int offset = size;
    int[] pixels = new int[size];
    int u, v, y1, y2, y3, y4;

    // i percorre os Y and the final pixels
    // k percorre os pixles U e V
    for(int i=0, k=0; i < size; i+=2, k+=2) {
        y1 = data[i  ]&0xff;
        y2 = data[i+1]&0xff;
        y3 = data[width+i  ]&0xff;
        y4 = data[width+i+1]&0xff;

        u = data[offset+k  ]&0xff;
        v = data[offset+k+1]&0xff;
        u = u-128;
        v = v-128;

        pixels[i  ] = convertYUVtoRGB(y1, u, v);
        pixels[i+1] = convertYUVtoRGB(y2, u, v);
        pixels[width+i  ] = convertYUVtoRGB(y3, u, v);
        pixels[width+i+1] = convertYUVtoRGB(y4, u, v);

        if (i!=0 && (i+2)%width==0)
            i+=width;
    }

    return pixels;
}

Solution

  • I solved the problem using setPixels() function:

    /**
     * @param bmp Must be mutable.
     * @param data
     */
    public static void correctWithByteArray(Bitmap bmp,int[] data) {
        bmp.setPixels(data,0,bmp.getWidth(),0,0,bmp.getWidth(),bmp.getHeight());
    }
    

    So I haven't found the answer to my question, but I solved my problem.