1
#include <jni.h>
#include <string>

#include <opencv2/opencv.hpp>
using namespace cv;

#include <iostream>

extern "C" JNIEXPORT jstring JNICALL
Java_com_example_cppinandroid_MainActivity_stringFromJNI( JNIEnv* env,
                            jobject)
{
    Mat image;
    image = imread( "/home/<name>/a.png", 1 );

    if ( !image.data )
    {
        return env->NewStringUTF( "No data in image!" );
    } else
    {
        return env->NewStringUTF( "Data is in image" );
    }
}

That's what I have in Native Cpp part of the android project.
When I run the application with emulator, it always shows: "No data in image!" text.

I have compiled this program separately as a normal c++ opencv program. It is working perfectly fine.
I have given the absolute path too. Is that not enough?

Do I have to write something in build.gradle also?

I am using Android studio, if that matters.

Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411

1 Answers1

2

Android directories do not match Linux at all.

A good solution is to find your file through Java and pass the path to the file as a parameter to function Java_com_example_cppinandroid_MainActivity_stringFromJNI.

If your file is in public files, you can try "/sdcard/a.png" - but the path may vary between different android shells.

The possible solution from reading from public files:

Java:

File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator + fileName);
if (f.exists()) {
foo(f.getAbsolutePath());

NDK:

extern "C" JNIEXPORT jstring JNICALL
Java_com_example_cppinandroid_MainActivity_stringFromJNI(JNIEnv* env,
                            jobject, jstring javaPath)
{
    const char* path = env->GetStringUTFChars(javaPath, 0);
    Mat image;
    image = imread( path, 1 );
    env->ReleaseStringUTFChars(javaPath, path );
    if ( !image.data )
    {
        return env->NewStringUTF( "No data in image!" );
    } else
    {
        return env->NewStringUTF( "Data is in image" );
    }
}

A better way to store a picture in assets and read AAssetManager like Android read text file from asset folder using C (ndk) or How to properly pass an asset FileDescriptor to FFmpeg using JNI in Android.

Neargye
  • 1,870
  • 1
  • 12
  • 12
  • Thank you. So, you mean to say that we just cannot fetch the file directly by giving absolute address in C++ in Android. There isn't a way to do it? – Aquarius_Girl May 09 '20 at 15:58
  • 1
    You can get the absolute path to public files through Environment.getExternalStorageDirectory().getAbsolutePath(). This method is easier to debug. – Neargye May 11 '20 at 11:49