android利用jni读取assets文件夹下的文件
一、概述
在jni的开发中,有时候会在c/c++层读取assets文件夹下的图片。
有两种方式可以选择:
方式一:在java/kotlin层把文件读取出来,然后以字符串的形式传递给jni层。
方式二:java/kotlin层传递一个文件名,jni利用AAssetManager读取文件内容
目前介绍的是第二种方案
二、代码示例
1.在cmake中引入android和jnigraphics
target_link_libraries( # Specifies the target library. opengl_filter opencv_java3 seeta_fa_lib # Links the target library to the log library # included in the NDK. ${log-lib} -lGLESv3 jnigraphics -landroid )
2.导入相关的头文件
//从assets文件夹中加载文件(图片或字符串) #include <assert.h> #include <android/asset_manager_jni.h> #include <android/asset_manager.h>
3.具体的执行方法
void loadBitmapFromAssets(AAssetManager *assetManager, const char *fileName) { AAsset *asset = AAssetManager_open(assetManager, fileName, AASSET_MODE_UNKNOWN); if (NULL == asset) { LOGE("asset is NULL"); } off_t bufferSize = AAsset_getLength(asset); LOGD("buffer size is %ld", bufferSize); unsigned char *imgBuff = (unsigned char *) malloc(bufferSize + 1); if (NULL == imgBuff) { LOGE("imgBuff alloc failed"); } memset(imgBuff, 0, bufferSize + 1); int readLen = AAsset_read(asset, imgBuff, bufferSize); LOGD("Picture read: %d", readLen); loadDataFromBuffer(imgBuff, readLen); if (imgBuff) { free(imgBuff); imgBuff = NULL; } AAsset_close(asset); }
分类:
JNI
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
2023-09-06 sentinel环境搭建及集合SpringBoot简单使用
2013-09-06 Android解决Intent中的数据重复问题