user3691371 user3691371 - 1 month ago 10
C++ Question

Get absolute path of images which located at drawable in android studio for NDK project

I am trying to pass path of images to my c++ file for using this image to image processing but I can not handle it just now.In my MainActivity I get the path like that :

Uri path;
String pathS;
path = Uri.parse("android.resource://com.sfarbac.rtmatching/" + R.drawable.elli);
pathS = path .toString();

and I passed this path to c++ file like that:

nativeClass.detectAndMatch(_mRgba.getNativeObjAddr(), _trick.getNativeObjAddr(), pathS);

I get the path information from native code like that:

(JNIEnv *env, jclass obj, jlong addrRgba, jlong addrTrick, jstring path){

Mat& camPic = *(Mat*)addrRgba;
Mat& camTric = *(Mat*)addrTrick;

const jsize len = env->GetStringUTFLength(path);
const char* strChars = env->GetStringUTFChars(path, (jboolean *)0);
string Result(strChars, len);

camTric = imread (Result.c_str(), CV_LOAD_IMAGE_GRAYSCALE);
if(! )
__android_log_print(ANDROID_LOG_ERROR, "TRACKERS", "%s", "Can not load image");
//return -1;
//cvtColor(camTric, camPic, CV_RGBA2GRAY);
env->ReleaseStringUTFChars(path, strChars);

return 1;


I can not load image here. I get error "Can not load image".
If I put my images in the asset folder, I know that I can not find them because these images are placed in the apk file. How do I get over this problem. Thanks.

Answer Source

Resources and assets are files on your development machine. They are not files on the device.

I am unclear why it would be useful to the user to perform image processing on a their device on a pre-compiled image. It would seem to make more sense to do that somewhere else, such as on your development machine. Or, perform image processing on images that come from the user, as opposed to pre-compiled ones.

That being said, either:

  • Adapt your C++ code to be able to work with a Java InputStream, or

  • Copy the bytes of the resource or asset to a file that you control (e.g., in getCacheDir()), then use the path to that file with your C++ code