Search code examples
c++file-ioandroid-ndkjava-native-interface

How to read an image in Hard drive in Android NDK?


I'm using Android NDK to make a simple app that draw an image. I run the app on my HTC M8 phone using Android 6.0. I use stb_image library (https://github.com/nothings/stb), which uses fopen to read the image . When I tried to load the image in my hard drive (It locates at "D:/Lighthouse.jpg"), I got the error because it couldn't open it with fopen, I'm sure the path to my image is correct. My code works fine in Visual Studio but not in Android. What am i doing wrong?

Update: I've searched around and add the following permission to my AndroidManifest.xml but it still doesn't work at all.

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

The error Log:

I/libgl2jni: Failed to load image: can't fopen
I/libgl2jni: Width =  = 1865550320
I/libgl2jni: Height =  = 1873207072
W/Adreno-ES20: <core_glTexImage2D:501>: GL_INVALID_VALUE

My image render class that call function loading image using fopen:

void generateTexture()
{

    glGenTextures(1 , &mTexture);
    glBindTexture(GL_TEXTURE_2D, mTexture);// Bind our 2D texture so that following set up will be applied

    //Set texture wrapping parameter
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_MIRRORED_REPEAT);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_MIRRORED_REPEAT);

    //Set texture Filtering parameter
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);

    //Load the image. This works fine in Visual Studio but not in Android Studio
    int picWidth,picHeight,n;
    unsigned char* image = stbi_load("D:/Lighthouse.jpg", &picWidth, &picHeight, &n,0);
    if (image == NULL ) {

        LOGI("Failed to load image: %s", stbi_failure_reason());

    }
    LOGI("Width =  = %d\n",
         picWidth);
    LOGI("Height =  = %d\n",
         picHeight);
    //Generate the image
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB , picWidth , picHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
    glGenerateMipmap(GL_TEXTURE_2D);

    stbi_image_free(image);// Free the reference to the image
    glBindTexture(GL_TEXTURE_2D,0); //Unbind 2D textures

}

Solution

  • From your Android devices you can only access the phone storage, you cannot access a file on your PC hard drive, at least not easily. Either put the file on the device storage, or a USB drive, or on a server.