简体   繁体   English

使用 ndk 从位图中计算像素

[英]Calculate pixel from bitmap using ndk

How can I calculate total amount of transparent color from a given bitmap using ndk如何使用 ndk 从给定的位图中计算透明色的总量

Java code:爪哇代码:

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

public native void calculatePixel(Bitmap bitmap);

Cpp code 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;
}

As I am new to ndk trying out image processing因为我是 ndk 的新手尝试图像处理

You can even rewrite the whole code你甚至可以重写整个代码

Since your pixel format is RGBA8888 , every fourth byte contains its alpha value.由于您的像素格式为RGBA8888 ,因此每四个字节包含其 alpha 值。 We can thus walk the bitmap line by line (where every line is info->stride bytes long), and there are info->height lines.因此,我们可以逐行遍历位图(其中每一行都是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);

Don't forget to AndroidBitmap_unlockPixels when you're done!完成后不要忘记AndroidBitmap_unlockPixels

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM