Android JNI處理圖片實(shí)現(xiàn)黑白濾鏡的方法
前言
在Android的開(kāi)發(fā)中,我們有時(shí)會(huì)遇到對(duì)性能要求比較高的模塊。所幸Android通過(guò)NDK為我們提供了c++開(kāi)發(fā)的方式。我們可以通過(guò)c++完成核心的耗時(shí)的計(jì)算,然后通過(guò)JNI的方式將處理完成的數(shù)據(jù)傳給Java層。
今天,我們就從一個(gè)很小的角度(Bitmap)的處理,來(lái)實(shí)踐NDK開(kāi)發(fā)的方式。開(kāi)發(fā)一個(gè)小小的圖片濾鏡。
準(zhǔn)備
新版本的Android Studio在新建工程時(shí),就可以選擇Include C++ support

當(dāng)我們勾上這個(gè)選擇后,Android Studio就會(huì)幫我們自動(dòng)完成,c++開(kāi)發(fā)目錄的創(chuàng)建。

我們先看一下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} )
我們可以看到,這個(gè)文件中,包含了我們需要使用的cpp庫(kù)和cpp文件。由于這一次的例子,我們需要開(kāi)發(fā)Bitmap相關(guān)的功能,所以我加入了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庫(kù)
*/
static {
System.loadLibrary("native-lib");
}
/**
* 點(diǎn)擊開(kāi)始加載圖片
* @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;
}
/**
* 處理圖片,此方法中會(huì)調(diào)用nativeProcessBitmap
* @param bitmap
* @return
*/
private Bitmap processBitmap(Bitmap bitmap) {
Bitmap bmp = bitmap.copy(Bitmap.Config.ARGB_8888, true);
nativeProcessBitmap( bmp);
return bmp;
}
}
代碼比較簡(jiǎn)單。不作過(guò)多的解釋。
與圖片相關(guān)的事情只有兩件:
- 引入native-lib庫(kù)
- 確定了native接口:public native void nativeProcessBitmap(Bitmap bitmap);
其他的代碼都是為了demo效果寫的一些業(yè)務(wù)代碼,不作過(guò)多贅述。
C++
由于c++的代碼比較長(zhǎng),我們分段來(lái)看。
#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
這一段主要引入了我們需要的庫(kù)并宏定義了eprintf,方便我們打日志并進(jìn)行調(diào)試。
#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的讀寫方法。對(duì)于RGB565和ARGB8888格式不熟悉的同學(xué),可以參考:
在Android的Bitmap.Config中有四個(gè)枚舉類型:ALPHA_8、ARGB_4444、ARGB_8888和RGB_565
下面是這四種類型的詳細(xì)解釋:
ALPHA_8:每個(gè)像素都需要1(8位)個(gè)字節(jié)的內(nèi)存,只存儲(chǔ)位圖的透明度,沒(méi)有顏色信息
ARGB_4444:A(Alpha)占4位的精度,R(Red)占4位的精度,G(Green)占4位的精度,B(Blue)占4位的精度,加起來(lái)一共是16位的精度,折合是2個(gè)字節(jié),也就是一個(gè)像素占兩個(gè)字節(jié)的內(nèi)存,同時(shí)存儲(chǔ)位圖的透明度和顏色信息。不過(guò)由于該精度的位圖質(zhì)量較差,官方不推薦使用
ARGB_8888:這個(gè)類型的跟ARGB_4444的原理是一樣的,只是A,R,G,B各占8個(gè)位的精度,所以一個(gè)像素占4個(gè)字節(jié)的內(nèi)存。由于該類型的位圖質(zhì)量較好,官方特別推薦使用。但是,如果一個(gè)480*800的位圖設(shè)置了此類型,那個(gè)它占用的內(nèi)存空間是:480*800*4/(1024*1024)=1.5M
RGB_565:同理,R占5位精度,G占6位精度,B占5位精度,一共是16位精度,折合兩個(gè)字節(jié)。這里注意的時(shí),這個(gè)類型存儲(chǔ)的只是顏色信息,沒(méi)有透明度信息
值得注意的是雖然RGB565的三色只有5位信息,但其實(shí)它們的值是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);
}
}
這一段代碼雖然長(zhǎng),但邏輯其實(shí)非常簡(jiǎn)單。
AndroidBitmapInfo bitmapInfo;
memset(&bitmapInfo , 0 , sizeof(bitmapInfo));
// Need add "jnigraphics" into target_link_libraries in CMakeLists.txt
AndroidBitmap_getInfo(env , bitmap , &bitmapInfo);
我們通過(guò)bitmap獲得AndroidBitmapInfo對(duì)象。AndroidBitmapInfo為我們提供了Bitmap的所有信息。
然后我們,再調(diào)用AndroidBitmap_lockPixels:
void * pixels = NULL; int res = AndroidBitmap_lockPixels(env, bitmap, &pixels);
獲得bitmap的像素矩陣,并將它存放在&pixels中。
pixels的每一位就包含了一個(gè)像素點(diǎn)的顏色信息。因此在RGB565模式下,它就是16位的,在ARGB8888模式下,它就是24位的。最后,我對(duì)RGB三色的值取了平均,從而得到一個(gè)新的圖片。在這個(gè)圖片中,RGB三色的值是相等的。因此,它是一個(gè)黑白圖片。
我們?cè)谛薷膱D片的像素值時(shí),圖片其實(shí)是被鎖定的,修改完成后,我們需要解鎖:
AndroidBitmap_unlockPixels(env, bitmap);
至此,我們的圖片修改就完成了。最后看一下效果。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android實(shí)現(xiàn)下載zip壓縮文件并解壓的方法(附源碼)
這篇文章主要給大家介紹了利用Android實(shí)現(xiàn)下載zip壓縮文件并解壓的方法,文中給出了示例代碼并提供了源碼下載,需要的朋友可以參考借鑒,下面來(lái)一起看看吧。2017-02-02
Android獲取與設(shè)置系統(tǒng)環(huán)境變量的方法指南
這篇文章主要給大家介紹了關(guān)于Android獲取與設(shè)置系統(tǒng)環(huán)境變量的方法指南,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)各位Android開(kāi)發(fā)者們具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06
Android網(wǎng)頁(yè)H5 Input選擇相機(jī)和系統(tǒng)相冊(cè)
這篇文章主要為大家詳細(xì)介紹了Android網(wǎng)頁(yè)H5 Input選擇相機(jī)和系統(tǒng)相冊(cè),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-10-10
android中GridView實(shí)現(xiàn)點(diǎn)擊查看更多功能示例
本篇文章主要介紹了android中GridView實(shí)現(xiàn)點(diǎn)擊查看更多功能示例,非常具有實(shí)用價(jià)值,需要的朋友可以參考下。2017-02-02
一文了解Android?ViewModelScope?如何自動(dòng)取消協(xié)程
這篇文章主要介紹了一文了解Android?ViewModelScope?如何自動(dòng)取消協(xié)程,文章圍繞主題站展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定參考價(jià)值,感興趣的小伙伴可以參考一下2022-07-07
解決ViewPager和SlidingPaneLayout的滑動(dòng)事件沖突問(wèn)題
下面小編就為大家分享一篇解決ViewPager和SlidingPaneLayout的滑動(dòng)事件沖突問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-01-01
Android錄制語(yǔ)音文件wav轉(zhuǎn)mp3的方法示例
這篇文章主要介紹了Android錄制語(yǔ)音文件wav轉(zhuǎn)mp3的方法示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-09-09
android popwindow實(shí)現(xiàn)左側(cè)彈出菜單層及PopupWindow主要方法介紹
PopupWindow可以實(shí)現(xiàn)浮層效果,主要方法有:可以自定義view,通過(guò)LayoutInflator方法;可以出現(xiàn)和退出時(shí)顯示動(dòng)畫(huà);可以指定顯示位置等感興趣的朋友可以了解下哦,希望本文對(duì)你學(xué)習(xí)android菜單相關(guān)開(kāi)發(fā)有所幫助2013-01-01

