JNI处理图片——黑白滤镜

前言

在Android的开发中,我们有时会遇到对性能要求比较高的模块。所幸Android通过NDK为我们提供了c++开发的方式。我们可以通过c++完成核心的耗时的计算,然后通过JNI的方式将处理完成的数据传给Java层。

今天,我们就从一个很小的角度(Bitmap)的处理,来实践NDK开发的方式。开发一个小小的图片滤镜。

准备

新版本的Android Studio在新建工程时,就可以选择Include C++ support

当我们勾上这个选择后,Android Studio就会帮我们自动完成,c++开发目录的创建。

我们先看一下CMakeLists.txt:

# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html

# Sets the minimum version of CMake required to build the native library.

cmake_minimum_required(VERSION 3.4.1)

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.

add_library( # Sets the name of the library.
             native-lib

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
             src/main/cpp/native-lib.cpp )

# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.

find_library( # Sets the name of the path variable.
              log-lib

              # Specifies the name of the NDK library that
              # you want CMake to locate.
              log )

# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.

target_link_libraries( # Specifies the target library.
                       native-lib jnigraphics

                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib} )

我们可以看到,这个文件中,包含了我们需要使用的cpp库和cpp文件。由于这一次的例子,我们需要开发Bitmap相关的功能,所以我加入了jnigraphics

Java

先看代码:

public class MainActivity extends AppCompatActivity {

    private ImageView mImg1, mImg2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mImg1 = (ImageView) findViewById(R.id.img_test1_id);
        mImg2 = (ImageView) findViewById(R.id.img_test2_id);
    }


    /**
     * 确定native处理图片的接口
     * @param bitmap 需要被处理的图片
     */
    public native void nativeProcessBitmap(Bitmap bitmap);

    /**
     * 引入native库
     */
    static {
        System.loadLibrary("native-lib");
    }

    /**
     * 点击开始加载图片
     * @param view
     */
    public void onLoadClick(View view) {
        Bitmap originalBitmap = loadBitmap();
        mImg1.setImageBitmap(originalBitmap);
        Bitmap resultBitmap = processBitmap(originalBitmap);
        mImg2.setImageBitmap(resultBitmap);
    }

    /**
     * 从assets中加载图片
     * @return
     */
    private Bitmap loadBitmap() {
        Bitmap bmp = null;
        AssetManager am = getResources().getAssets();
        try {
            InputStream is = am.open("test_img.jpg");
            BitmapFactory.Options options = new BitmapFactory.Options();
            bmp = BitmapFactory.decodeStream(is ,null , options);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bmp;
    }

    /**
     * 处理图片,此方法中会调用nativeProcessBitmap
     * @param bitmap
     * @return
     */
    private Bitmap processBitmap(Bitmap bitmap) {
        Bitmap bmp = bitmap.copy(Bitmap.Config.ARGB_8888, true);
        nativeProcessBitmap( bmp);
        return bmp;
    }
}

代码比较简单。不作过多的解释。
与图片相关的事情只有两件:

  1. 引入native-lib
  1. 确定了native接口:public native void nativeProcessBitmap(Bitmap bitmap);

其他的代码都是为了demo效果写的一些业务代码,不作过多赘述。

C++

由于c++的代码比较长,我们分段来看。

#include <jni.h>
#include <string>

#include <android/bitmap.h>
#include <android/log.h>

#ifndef eprintf
#define eprintf(...) __android_log_print(ANDROID_LOG_ERROR,"@",__VA_ARGS__)

#endif

这一段主要引入了我们需要的库并宏定义了eprintf,方便我们打日志并进行调试。

#define MAKE_RGB565(r,g,b) ((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3))
#define MAKE_ARGB(a,r,g,b) ((a&0xff)<<24) | ((r&0xff)<<16) | ((g&0xff)<<8) | (b&0xff)

#define RGB565_R(p) ((((p) & 0xF800) >> 11) << 3)
#define RGB565_G(p) ((((p) & 0x7E0 ) >> 5)  << 2)
#define RGB565_B(p) ( ((p) & 0x1F  )        << 3)

#define RGB8888_A(p) (p & (0xff<<24) >> 24 )
#define RGB8888_R(p) (p & (0xff<<16) >> 16 )
#define RGB8888_G(p) (p & (0xff<<8)  >> 8 )
#define RGB8888_B(p) (p & (0xff) )

这一段定义了RGB565和ARGB8888的读写方法。对于RGB565和ARGB8888格式不熟悉的同学,可以参考:

http://blog.csdn.net/fence2012/article/details/44928871

值得注意的是虽然RGB565的三色只有5位信息,但其实它们的值是8位,提供的5位信息是高5位的信息。

extern "C"
{

    JNIEXPORT void JNICALL
    Java_com_live_longsiyang_jnibitmapdemo_MainActivity_nativeProcessBitmap(JNIEnv *env,
                                                                            jobject instance,
                                                                            jobject bitmap) {

        if (bitmap == NULL) {
            eprintf("bitmap is null\n");
            return;
        }

        AndroidBitmapInfo bitmapInfo;
        memset(&bitmapInfo , 0 , sizeof(bitmapInfo));
        // Need add "jnigraphics" into target_link_libraries in CMakeLists.txt
        AndroidBitmap_getInfo(env , bitmap , &bitmapInfo);

        // Lock the bitmap to get the buffer
        void * pixels = NULL;
        int res = AndroidBitmap_lockPixels(env, bitmap, &pixels);

        // From top to bottom
        int x = 0, y = 0;
        for (y = 0; y < bitmapInfo.height; ++y) {
            // From left to right
            for (x = 0; x < bitmapInfo.width; ++x) {
                int a = 0, r = 0, g = 0, b = 0;
                void *pixel = NULL;
                // Get each pixel by format

                if(bitmapInfo.format == ANDROID_BITMAP_FORMAT_RGBA_8888)
                {
                    pixel = ((uint32_t *)pixels) + y * bitmapInfo.width + x;
                    int r,g,b;
                    uint32_t v = *((uint32_t *)pixel);
                    r = RGB8888_R(v);
                    g = RGB8888_G(v);
                    b = RGB8888_B(v);
                    int sum = r+g+b;
                    *((uint32_t *)pixel) = MAKE_ARGB(0x1f , sum/3, sum/3, sum/3);
                }
                else if (bitmapInfo.format == ANDROID_BITMAP_FORMAT_RGB_565) {
                    pixel = ((uint16_t *)pixels) + y * bitmapInfo.width + x;
                    int r,g,b;
                    uint16_t v = *((uint16_t *)pixel);
                    r = RGB565_R(v);
                    g = RGB565_G(v);
                    b = RGB565_B(v);
                    int sum = r+g+b;
                    *((uint16_t *)pixel) = MAKE_RGB565(sum/3, sum/3, sum/3);  }
            }
        }

        AndroidBitmap_unlockPixels(env, bitmap);

    }

}

这一段代码虽然长,但逻辑其实非常简单。

        AndroidBitmapInfo bitmapInfo;
        memset(&bitmapInfo , 0 , sizeof(bitmapInfo));
        // Need add "jnigraphics" into target_link_libraries in CMakeLists.txt
        AndroidBitmap_getInfo(env , bitmap , &bitmapInfo);

我们通过bitmap获得AndroidBitmapInfo对象。AndroidBitmapInfo为我们提供了Bitmap的所有信息。

然后我们,再调用AndroidBitmap_lockPixels:

        void * pixels = NULL;
        int res = AndroidBitmap_lockPixels(env, bitmap, &pixels);

获得bitmap的像素矩阵,并将它存放在&pixels中。

pixels的每一位就包含了一个像素点的颜色信息。因此在RGB565模式下,它就是16位的,在ARGB8888模式下,它就是24位的。最后,我对RGB三色的值取了平均,从而得到一个新的图片。在这个图片中,RGB三色的值是相等的。因此,它是一个黑白图片。

我们在修改图片的像素值时,图片其实是被锁定的,修改完成后,我们需要解锁:

        AndroidBitmap_unlockPixels(env, bitmap);

至此,我们的图片修改就完成了。最后看一下效果。

如有问题,欢迎指正。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,408评论 4 371
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,690评论 2 307
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 112,036评论 0 255
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,726评论 0 221
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,123评论 3 296
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,037评论 1 225
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,178评论 2 318
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,964评论 0 213
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,703评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,863评论 2 254
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,333评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,658评论 3 263
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,374评论 3 244
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,195评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,988评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,167评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,970评论 2 279

推荐阅读更多精彩内容