Search code examples
androidimage-processingbitmapcocos2d-x

Inter change blue and red channels in bitmap in android


I am using the following code to get pixel data from a bitmap and then passing the array through JNI to cocos2dx. When I render the image in cocos2d-x the Red and Blue channels are reversed. Is there a way to access the red, blue channels separately from the pixel's int value and then inter-change them?

JAVA CODE

    int[] pixels = new int[bitmap.getWidth() * bitmap.getHeight()];
    bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
    int len = bitmap.getWidth() * bitmap.getHeight();
    onFacebookImageNative(pixels, len, bitmap.getWidth(), bitmap.getHeight(), bitsPerComponent);

JNI CODE

JNIEXPORT void JNICALL Java_com_xxxx_yyyyo_yyyyo_onFacebookImageNative(JNIEnv* env, jobject,
    jintArray pixels, jint dataLen, jint width, jint height, jint bitsPerComponent)
{
yyyyo *yyyyo = yyyyo::singleton();

jint *jArr = env->GetIntArrayElements(pixels, NULL);
int pixelsInt[dataLen];
for (int i=0; i<dataLen; i++){
    pixelsInt[i] = (int)jArr[i];
}

yyyyo->onFacebookImage(pixelsInt, (int) dataLen,
        CCImage::kFmtRawData, (int) width, (int) height, (int) bitsPerComponent);
}

Solution

  • Ok, may be I asked the question too early without trying too hard.

    JAVA CODE

        int[] pixels = new int[bitmap.getWidth() * bitmap.getHeight()];
        bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
    
        int[] finalArray = new int[bitmap.getWidth() * bitmap.getHeight()];
    
        for(int i = 0; i < len; i++) {
    
        int red = Color.red(pixels[i]);
        int green = Color.green(pixels[i]);
        int blue = Color.blue(pixels[i]);
        finalArray[i] = Color.rgb(blue, green, red);//invert sequence here.
        }
    
    
        int len = bitmap.getWidth() * bitmap.getHeight();
        onFacebookImageNative(pixels, len, bitmap.getWidth(), bitmap.getHeight(), bitsPerComponent);
    

    If anyone has a better answer that does not involve iterating through each pixel, then please share it here.