JNI之Bitmap灰度图(RGBA_8888和RGB_565)

JNI之Bitmap灰度图

RGBA_888832
RGB_56516

实现代码如下:

AndroidBitmapInfo info;
AndroidBitmap_getInfo(env, bitmap, &info);
void *pixels;
AndroidBitmap_lockPixels(env, bitmap, &pixels);

if (info.format == ANDROID_BITMAP_FORMAT_RGBA_8888) {
    LOGD("format : RGBA_8888");
    // 灰度处理
    for (int i = 0; i < info.width * info.height; i++) {
        uint32_t *pixel_p = static_cast<uint32_t *>(pixels) + i;
        uint32_t pixel = *pixel_p;
        int a = (pixel >> 24) & 0xff; //8
        int r = (pixel >> 16) & 0xff; //8
        int g = (pixel >> 8) & 0xff;  //8
        int b = (pixel) & 0xff;       //8
        int gray = (int) (0.213f * r + 0.715f * g + 0.072f * b); // 32位的公式
//            int gray = (r * 38 + g * 75 + b * 15) >> 7;
        *pixel_p = (a << 24) | (gray << 16) | (gray << 8) | gray;
    }
    LOGD("RGBA_8888 end");
} else if (info.format == ANDROID_BITMAP_FORMAT_RGB_565) {
    LOGD("format : RGB_565");
    for (int i = 0; i < info.width * info.height; i++) {
        uint16_t *pixel_p = static_cast<uint16_t *>(pixels) + i;
        uint16_t pixel = *pixel_p;
        int r = ((pixel >> 11) & 0x1f) << 3; //5 补位为8位
        int g = ((pixel >> 5) & 0x3f) << 2;  //6 补位为8位
        int b = ((pixel) & 0x1f) << 3;       //5 补位为8位
        int gray = (int) (0.213f * r + 0.715f * g + 0.072f * b); // 32位的公式
//            int gray = (r * 38 + g * 75 + b * 15) >> 7;
        *pixel_p = ((gray>>3) << 11) | ((gray>>2) << 5) | (gray >> 3);
    }
    LOGD("RGB_565 end");
}
AndroidBitmap_unlockPixels(env, bitmap);

你可能感兴趣的:(Android,android,jni,bitmap)