[Android]通过JNI访问并操作Bitmap的元素,支持RGB565和ARGB8888
16lz
2021-01-26
一段简单的JNI例子,输入是Bitmap(需要是Mutable),结果是把Bitmap变成灰度图。
为了看起来有点价值,所以同时支持了RGB565和ARGB8888(囧rz)
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <stdint.h>#include <jni.h>#include <android/bitmap.h>#include <android/log.h>#ifndef eprintf#define eprintf(...) __android_log_print(ANDROID_LOG_ERROR,"@",__VA_ARGS__)#endif#define RGB565_R(p) ((((p) & 0xF800) >> 11) << 3)#define RGB565_G(p) ((((p) & 0x7E0 ) >> 5) << 2)#define RGB565_B(p) ( ((p) & 0x1F ) << 3)#define MAKE_RGB565(r,g,b) ((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3))#define RGBA_A(p) (((p) & 0xFF000000) >> 24)#define RGBA_R(p) (((p) & 0x00FF0000) >> 16)#define RGBA_G(p) (((p) & 0x0000FF00) >> 8)#define RGBA_B(p) ((p) & 0x000000FF)#define MAKE_RGBA(r,g,b,a) (((a) << 24) | ((r) << 16) | ((g) << 8) | (b))JNIEXPORT void JNICALL Java_com_yxcorp_hello_Effect_update (JNIEnv *env, jclass clazz, jobject zBitmap) {JNIEnv J = *env;if (zBitmap == NULL) {eprintf("bitmap is null\n");return;}// Get bitmap infoAndroidBitmapInfo info;memset(&info, 0, sizeof(info));AndroidBitmap_getInfo(env, zBitmap, &info);// Check format, only RGB565 & RGBA are supportedif (info.width <= 0 || info.height <= 0 ||(info.format != ANDROID_BITMAP_FORMAT_RGB_565 && info.format != ANDROID_BITMAP_FORMAT_RGBA_8888)) {eprintf("invalid bitmap\n");J->ThrowNew(env, J->FindClass(env, "java/io/IOException"), "invalid bitmap");return;}// Lock the bitmap to get the buffervoid * pixels = NULL;int res = AndroidBitmap_lockPixels(env, zBitmap, &pixels);if (pixels == NULL) {eprintf("fail to lock bitmap: %d\n", res);J->ThrowNew(env, J->FindClass(env, "java/io/IOException"), "fail to open bitmap");return;}eprintf("Effect: %dx%d, %d\n", info.width, info.height, info.format);int x = 0, y = 0;// From top to bottomfor (y = 0; y < info.height; ++y) {// From left to rightfor (x = 0; x < info.width; ++x) {int a = 0, r = 0, g = 0, b = 0;void *pixel = NULL;// Get each pixel by formatif (info.format == ANDROID_BITMAP_FORMAT_RGB_565) {pixel = ((uint16_t *)pixels) + y * info.width + x;uint16_t v = *(uint16_t *)pixel;r = RGB565_R(v);g = RGB565_G(v);b = RGB565_B(v);} else {// RGBApixel = ((uint32_t *)pixels) + y * info.width + x;uint32_t v = *(uint32_t *)pixel;a = RGBA_A(v);r = RGBA_R(v);g = RGBA_G(v);b = RGBA_B(v);}// Grayscaleint gray = (r * 38 + g * 75 + b * 15) >> 7;// Write the pixel backif (info.format == ANDROID_BITMAP_FORMAT_RGB_565) {*((uint16_t *)pixel) = MAKE_RGB565(gray, gray, gray);} else {// RGBA*((uint32_t *)pixel) = MAKE_RGBA(gray, gray, gray, a);}}}AndroidBitmap_unlockPixels(env, zBitmap);}
更多相关文章
- Android(安卓)EditText限制输入数字和字母
- android 系统搜索框的使用及获取输入
- Android(安卓)自定义View 例子一
- android背景图片更换――经典例子
- 横屏的时候使用EditText,输入法半屏显示
- android中自定义service的详解(例子)
- 百度地图开发 android App 数字签名(SHA1)获取办法
- EditText常用属性【一】:空白提示/文本域/特殊字符/数字类型/等
- android手写输入