How to convert content:// Uri into actual file path?

后端 未结 2 665
余生分开走
余生分开走 2021-02-15 00:56

how can I get the actual file path on the SD card where a content:// uri is pointing for an image?

相关标签:
2条回答
  • 2021-02-15 01:58

    I've adapted the code which @hooked82 linked to:

    protected String convertMediaUriToPath(Uri uri) {
        String [] proj={MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(uri, proj,  null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String path = cursor.getString(column_index); 
        cursor.close();
        return path;
    }
    
    0 讨论(0)
  • 2021-02-15 02:01

    Content URIs have syntax content://authority/path/id, read here. Parse id from content URI and query MediaStore.Images.Media.EXTERNAL_CONTENT_URI as follows:

    long id = ContentUris.parseId(Uri.parse(contentUri));
    Cursor cursor = getContentResolver()
                .query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[]{ MediaStore.Images.Media.DATA },
                        MediaStore.Images.Media._ID + " = ?", new String[]{ Long.toString(id) }, 
                        null);
    if (cursor.moveToNext()) {
        path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
    }
    cursor.close();
    
    0 讨论(0)
提交回复
热议问题