Android JNI Bitmap指定颜色值替换

复制代码
#include <jni.h>
#include <string>
#include <android/bitmap.h>
#include <cmath>
#include <android/log.h>
//定义TAG之后,我们可以在LogCat通过TAG过滤出NDK打印的日志
#define TAG "BitmapOperationNative"
// 定义info信息
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,TAG,__VA_ARGS__)

void operationBitmap(JNIEnv *env, jobject bitmap, int srcColor, int dstColor) {
    int result;
    // 获取源Bitmap相关信息:宽、高等
    AndroidBitmapInfo sourceInfo;
    result = AndroidBitmap_getInfo(env, bitmap, &sourceInfo);
    if (result < 0) {
        LOGI(" AndroidBitmap_getInfo result=%d ", result);
        return;
    }
    LOGI(" AndroidBitmapInfo format=%d srcColor=%x dstColor=%x", sourceInfo.format, srcColor,
         dstColor);
    // 获取源Bitmap像素数据 这里用的是32位的int类型 argb每个8位
    uint32_t *sourceData;
    //锁定像素的地址(不锁定的话地址可能会发生改变)
    result = AndroidBitmap_lockPixels(env, bitmap, (void **) &sourceData);
    if (result < 0) {
        LOGI(" AndroidBitmap_lockPixels result=%d ", result);
        return;
    }
    // 遍历各个像素点
    int color;
    int red, green, blue, alpha;
    int width = sourceInfo.width;
    int height = sourceInfo.height;
    int w, h;
    for (h = 0; h < height; h++) {
        for (w = 0; w < width; w++) {
            color = sourceData[h * width + w];
            if (color == srcColor) {
                sourceData[h * width + w] = dstColor;
            }
        }
    }
    AndroidBitmap_unlockPixels(env, bitmap);
}

extern "C"
JNIEXPORT void JNICALL
Java_com_istep_bitmap_BitmapOperationNative_convertTo(JNIEnv *env, jclass clazz, jobject bitmap,
                                                      jint src, jint dst) {
    operationBitmap(env, bitmap, src, dst);
}
相关推荐
aaajj14 小时前
【Android】关于MY_PACKAGE_REPLACED广播
android
4Forsee15 小时前
【Android】动态操作 Window 的背后机制
android·java·前端
华锋202215 小时前
2025.12首次体验 arkui-x 跨平台开发库
android
allk5516 小时前
Android 性能优化之启动加速:从底层原理到架构治理
android
QuantumLeap丶17 小时前
《Flutter全栈开发实战指南:从零到高级》- 24 -集成推送通知
android·flutter·ios
用户416596736935517 小时前
WebView 滚动失灵?剖析 `scrollBy()` 在现代 Web 布局中的失效陷阱
android
明川17 小时前
Android Gradle学习 - Gradle插件开发与发布指南
android·前端·gradle
二流小码农18 小时前
鸿蒙开发:上架困难?谈谈我的上架之路
android·ios·harmonyos
Propeller18 小时前
【Android】动态操作 Window 的背后机制
android·java