四.NDK处理Bitmap灰度

Bitmap的处理,是NDK知识中很重要的一部分,本篇文章将讲解一些常用的NDK如何处理bitmap

一.编写BitmapUtil

BitmapUti.h

#ifndef PRACTICLE_BITMAPUTIL_H
#define PRACTICLE_BITMAPUTIL_H

#include <jni.h>
#include <android/bitmap.h>
class BitmapUtil {
public:
    int gray(JNIEnv *env, jobject bitmap);
};

BitmapUtil的实现


int BitmapUtil::gray(JNIEnv *env, jobject bitmap) {
    AndroidBitmapInfo srcInfo;
    //获取bitmap属性信息
    if (ANDROID_BITMAP_RESULT_SUCCESS != AndroidBitmap_getInfo(env, bitmap, &srcInfo)) {
        return false;
    }

    void *srcBuf;
    //获取bitmap的像素信息,并锁住当前的像素点
    if (ANDROID_BITMAP_RESULT_SUCCESS != AndroidBitmap_lockPixels(env, bitmap, &srcBuf)) {
        return false;
    }
    int w = srcInfo.width;
    int h = srcInfo.height;

    int32_t *srcPixs = (int32_t *) srcBuf;

    int alpha = 0xFF << 24;
    for (int i = 0; i < h; i++) {
        for (int j = 0; j < w; j++) {
            // 获得像素的颜色
            int color = srcPixs[w * i + j];
            int red = ((color & 0x00FF0000) >> 16);
            int green = ((color & 0x0000FF00) >> 8);
            int blue = color & 0x000000FF;
            color = (red + green + blue) / 3;
            color = alpha | (color << 16) | (color << 8) | color;
            srcPixs[w * i + j] = color;
        }
    }
    //修改完,解锁操作
    AndroidBitmap_unlockPixels(env, bitmap);
    return true;
};

计算灰度图片的公式 (R+G+B)/3

二.NDK的映射函数

Hello.cpp

#include <Hello.h>
#ifdef __cplusplus
extern "C" {
#endif


JNIEXPORT jint JNICALL
Java_com_example_a4_1datatype_1bitmap_MainActivity_gray(JNIEnv *env, jobject instance, jobject bitmap){
    BitmapUtil *bitmapUtil = new BitmapUtil;
    bitmapUtil->gray(env, bitmap);
    delete bitmapUtil;
    return JNI_TRUE;
}

#ifdef __cplusplus
}
#endif

MainActivity的Native函数

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView srcIv = findViewById(R.id.iv_src);
        ImageView dstIv = findViewById(R.id.iv_det);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.google);
        if (gray(bitmap) == 1) {
            dstIv.setImageBitmap(bitmap);
        }
    }
    static {
        //加载静态库
        System.loadLibrary("native-lib");
    }
    public native int gray(Bitmap bitmap);
}

三.实际效果

在这里插入图片描述

code:https://github.com/HumorSmith/NDKPraticle/tree/master/4_datatype_bitmap

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页