使用ndk从位图中计算像素

Calculate pixel from bitmap using ndk

如何使用 ndk 计算给定位图中的透明颜色总量

Java代码:

    static {
    System.loadLibrary("bitmap-processing");
}

public native void calculatePixel(Bitmap bitmap);

Cpp代码

extern "C" JNIEXPORT jobject JNICALL
Java_com_example_myapplication_CustomLayout_calculatePixel(JNIEnv *env, jobject thiz,
                                                       jobject bitmap) {
uint8_t *bitmapPixel;

AndroidBitmapInfo info;

if (AndroidBitmap_getInfo(env, bitmap, &info) < 0) {
    __android_log_print(ANDROID_LOG_INFO, "bitmap-processing", "ret valude = %d",
                        AndroidBitmap_getInfo(env, bitmap, &info));
    return NULL;
}

if ((AndroidBitmap_lockPixels(env, bitmap, static_cast<void **>((void *) bitmapPixel))) < 0){
    __android_log_print(ANDROID_LOG_INFO, "bitmap-processing", "Bitmap type error");
    return NULL;
}

struct pixel { uint8_t r, g, b, a; };
uint32_t num_transparent = 0;
for (int y = 0; y < info.height; y++) {
    pixel* row = (pixel *)(bitmapPixel + y * info.stride);
    for (int x = 0; x < info.width; x++) {
        const pixel& p = row[x];
        if (p.a == 0)
            num_transparent++;
    }
}

float proportion_transparent = float(num_transparent) / (info.width * info.height);

__android_log_print(ANDROID_LOG_INFO, "Bitmap-processing", "Transparent value : %f", proportion_transparent);

AndroidBitmap_unlockPixels(env, bitmap);
return nullptr;
}

因为我是 ndk 的新手,尝试图像处理

你甚至可以重写整个代码

由于您的像素格式是 RGBA8888,每第四个字节包含其 alpha 值。 因此,我们可以逐行遍历位图(每行 info->stride 字节 长),并且有 info->height 行。

uint8_t* bitmapPixel;
if ((AndroidBitmap_lockPixels(env, bitmap, (void **)&bitmapPixel)) < 0){
    __android_log_print(ANDROID_LOG_INFO, "bitmap-processing", "Bitmap type error");
    return NULL;
}

struct pixel { uint8_t r, g, b, a; };
uint32_t num_transparent = 0;
for (int y = 0; y < info->height; y++) {
    pixel* row = (pixel *)(bitmapPixel + y * info->stride);
    for (int x = 0; x < info->width; x++) {
        const pixel& p = row[x];
        if (p.a == 0)
            num_transparent++;
    }
}

float proportion_transparent = float(num_transparent) / (info->width * info->height);

完成后别忘了AndroidBitmap_unlockPixels