温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android中JNI处理图片如何实现黑白滤镜

发布时间:2021-08-04 14:42:47 来源:亿速云 阅读:139 作者:小新 栏目:移动开发

这篇文章将为大家详细讲解有关Android中JNI处理图片如何实现黑白滤镜,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

准备

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

Android中JNI处理图片如何实现黑白滤镜

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

Android中JNI处理图片如何实现黑白滤镜

我们先看一下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库

  2. 确定了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格式不熟悉的同学,可以参考:

在Android的Bitmap.Config中有四个枚举类型:ALPHA_8、ARGB_4444、ARGB_8888和RGB_565

下面是这四种类型的详细解释:

ALPHA_8:每个像素都需要1(8位)个字节的内存,只存储位图的透明度,没有颜色信息

ARGB_4444:A(Alpha)占4位的精度,R(Red)占4位的精度,G(Green)占4位的精度,B(Blue)占4位的精度,加起来一共是16位的精度,折合是2个字节,也就是一个像素占两个字节的内存,同时存储位图的透明度和颜色信息。不过由于该精度的位图质量较差,官方不推荐使用

ARGB_8888:这个类型的跟ARGB_4444的原理是一样的,只是A,R,G,B各占8个位的精度,所以一个像素占4个字节的内存。由于该类型的位图质量较好,官方特别推荐使用。但是,如果一个480*800的位图设置了此类型,那个它占用的内存空间是:480*800*4/(1024*1024)=1.5M

RGB_565:同理,R占5位精度,G占6位精度,B占5位精度,一共是16位精度,折合两个字节。这里注意的时,这个类型存储的只是颜色信息,没有透明度信息

值得注意的是虽然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);

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

Android中JNI处理图片如何实现黑白滤镜

关于“Android中JNI处理图片如何实现黑白滤镜”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI