我有一个本地 android 项目,它获取当前应用程序的内部存储目录,还可以操作从 java 传递到 c++ 的位图的像素。
我的目标是能够从该位置读取图像文件作为 C 本身中的作业对象,这样我就可以返回调用函数。问题是我希望避免使用 java 调用来检索位图本身,并希望它完全由 Native 完成。 (即,与 env->CallObjectMethod 完全不同)
到目前为止,我的代码获取了所需图像文件的位置/文件名,但我确实有另一个 native 文件,它可以正确处理/处理传入的位图(使用 bitmap.h),但因为它是在之后使用的,并且我对它很满意我没有包括它。这是路径/文件名代码:
#include "frameConstruction.h"
#include <string>
#include <unistd.h>
using namespace std;
#define LOG_TAG "TAG"
//macros to call the Log functions to allow for debugging. the tag is declared on the line above
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
JNIEXPORT jstring JNICALL Java_com_example_ndkbitmapcreation_FrameConstructionLib_constructFrame(
JNIEnv* env, jobject obj, jobject javaThis, jstring stringSomething) {
jclass cls = env->GetObjectClass(javaThis);
jmethodID getFilesDir = env->GetMethodID(cls, "getFilesDir",
"()Ljava/io/File;");
jobject dirobj = env->CallObjectMethod(javaThis, getFilesDir);
jclass dir = env->GetObjectClass(dirobj);
jmethodID getStoragePath = env->GetMethodID(dir, "getAbsolutePath",
"()Ljava/lang/String;");
jstring path = (jstring) env->CallObjectMethod(dirobj, getStoragePath);
const char *pathstr = env->GetStringUTFChars(path, 0);
std::string fullPath = std::string(pathstr);
chdir(pathstr);
env->ReleaseStringUTFChars(path, pathstr);
const char *filenamestr = env->GetStringUTFChars(stringSomething, 0);
//need code here to call the File.separator method from java,
//if someone knows how to do this that'd be great, currently
//this just grabs the first char from the path which is (hopefully)
//the proper file separator
fullPath += fullPath[0];
fullPath += filenamestr;
env->ReleaseStringUTFChars(stringSomething, filenamestr);
//pixel manip will go here
return env->NewStringUTF(fullPath.c_str());
}
那么我将如何在不调用 java 方法的情况下将该文件中的数据读入可作为位图返回的 jobject(即:return varName;)?或者我可以将它读入字节数组,例如:JNI in C++ to read file to jbyteArray那么问题就变成了如何在不调用 Java 的情况下将 jbytearray 更改为可再次使用的 jobject?
我希望避免在 java 中制作位图然后将其传递给 c++,但我的代码需要大量位图加载/操作并导致 java 中出现 OOM 错误,因此我正在尝试使用 Native 中的一种方法来尽量避免它。这是一个长达数月的项目,希望这是最后的障碍之一,如果有人能提供帮助,我将不胜感激 ^_^。
最佳答案
我敢肯定,如果不调用 java 方法,就不可能在 native 代码中创建位图。
如果您熟悉 bitmap.h
header ,您会发现它只提供了非常有限的可能性:您可以在 native 中编辑位图,但不能创建它。
您仍然可以通过从代码的 NDK 部分调用位图构造函数来避免编写 java 代码!
关于android ndk,如何将图像文件读取到位图jobject?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20340558/