1

Recently I'm doing some stuff on Android using JNI and C++

I want to write the result to the android file system with cv::imwrite() to check if I'm doing right, however, there is no file written into it. I also tried to write text file, failed again.

Here is part of my code. Is there anything I'm doing wrong? Thanks for your help!

JNIEXPORT void JNICALL Java_com_project_NativeLibs_test(JNIEnv *env, jclass clazz
{
    LOGV("test CALLED");

    std::string file1, file2, outFile;
    file1 = "/sdcard/test_data/images/box.pgm";
    file2 = "/sdcard/test_data/images/scene.pgm";
    outFile = "/sdcard/output_data/JNI_after.png";

    cv::Mat objectImg = cv::imread(file1, cv::IMREAD_GRAYSCALE);
    cv::Mat sceneImg =  cv::imread(file2, cv::IMREAD_GRAYSCALE);
    cv::Mat out;

    // ... some Mat process get output to Mat out

    cv::imwrite(outFile, out);

    std::ofstream filetest;
    filetest.open("test.txt");
    filetest<<"writing from JNI";
    filetest.close();

    LOGV("Done Finally");

}

junhan
  • 119
  • 4
  • 11
  • Are you sure about that path? Not all devices mount the sdcard in the same spot (in fact not all of them have an SD card). You should never hard code it in Android- it should be passed in from the Java which can ask for the path. – Gabe Sechan Jul 08 '14 at 21:14
  • I'm quite sure about the path because I can read images rightly. As I searched several examples, I found other people do hard code and it works. But your advice is worth trying! Thank you! – junhan Jul 08 '14 at 21:52
  • In addition, I use adb shell to search the whole file system and found my file is not written into – junhan Jul 08 '14 at 22:21
  • It will work on some devices. That code fails on 2 out of 3 of mine- that isn't the path to the sd card. – Gabe Sechan Jul 08 '14 at 23:36
  • No, it's not included in the default location. I used `mkdir` to create these two folders before execute this piece of code. – junhan Jul 09 '14 at 04:38
  • Are you using android 4.4 or something older? You're limited to where you can write on Android 4.4+- you can only write to the sd card in your private directory. – Gabe Sechan Jul 09 '14 at 05:26
  • That may make sense, I'm using android 4.4. But these two floders are private, aren't they? – junhan Jul 10 '14 at 18:37
  • No. Private would be the directory returned by Content.getExternalFilesDir() and subfolders. – Gabe Sechan Jul 10 '14 at 18:50
  • Check out this article, it might help http://www.androidcentral.com/kitkat-sdcard-changes – Gabe Sechan Jul 10 '14 at 18:58
  • That's great, let me try it out. Thank you very for your time! – junhan Jul 11 '14 at 21:40

1 Answers1

2

Maybe you need to add this:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

from: Android: OpenCV: imwrite always returns false and fails to write

Community
  • 1
  • 1
Skeitho
  • 113
  • 1
  • 9