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);
    }

 

posted on 2024-09-06 17:13  飘杨......  阅读(31)  评论(0编辑  收藏  举报