Android提高之使用NDK把彩图转换灰度图的方法(2)
封装NDK函数的JAVA类LibFuns.java的源码如下: package com.testToGray; public class LibFuns { static { System.loadLibrary("ImgToGray"); } /** * @param width the current view width * @param he
封装NDK函数的JAVA类LibFuns.java的源码如下:
package com.testToGray;
public class LibFuns {
static {
System.loadLibrary("ImgToGray");
}
/**
* @param width the current view width
* @param height the current view height
*/
public static native int[] ImgToGray(int[] buf, int w, int h);
}
彩图转换为灰度图的ImgToGray.cpp源码:
#include <jni.h>
#include <stdio.h>
#include <stdlib.h>
extern "C" {
JNIEXPORT jintArray JNICALL Java_com_testToGray_LibFuns_ImgToGray(
JNIEnv* env, jobject obj, jintArray buf, int w, int h);
}
;
JNIEXPORT jintArray JNICALL Java_com_testToGray_LibFuns_ImgToGray(
JNIEnv* env, jobject obj, jintArray buf, int w, int h) {
jint *cbuf;
cbuf = env->GetIntArrayElements(buf, false);
if (cbuf == NULL) {
return 0; /* exception occurred */
}
int alpha = 0xFF << 24;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
// 获得像素的颜色
int color = cbuf[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;
cbuf[w * i + j] = color;
}
}
int size=w * h;
jintArray result = env->NewIntArray(size);
env->SetIntArrayRegion(result, 0, size, cbuf);
env->ReleaseIntArrayElements(buf, cbuf, 0);
return result;
}
Android.mk的源码:
LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := ImgToGray LOCAL_SRC_FILES := ImgToGray.cpp include $(BUILD_SHARED_LIBRARY)
感兴趣的读者可以动手调试一下本文所述代码,相信会对大家进行Android项目开发有一定的帮助。
收藏文章
精彩图集
精彩文章





