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;
}
}
代码比较简单。不作过多的解释。
与图片相关的事情只有两件:
- 引入
native-lib
库
- 确定了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格式不熟悉的同学,可以参考:
值得注意的是虽然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);
至此,我们的图片修改就完成了。最后看一下效果。
如有问题,欢迎指正。