从相机的图片中恢复真实路径



我正在从相机拍摄照片并保存在公共文件夹(图片/myFolder(中,并且我正在存储图片中的 Uri 以重新加载到我的视图中,但我需要构建一个具有真实路径的文件,但我无法恢复路径,他们在互联网上找到的所有代码都给了我空指针,我怎样才能恢复真实路径?

URI 示例

content://media/content://br.com.technolog.darwinchecklist.fileprovider/darwin_checklist_images/DARWIN_20180827_114154_460340375.jpg/images/media

不起作用的方法

public String getRealPathFromURI(Uri uri) {
String path = "";
if (getContentResolver() != null) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
path = cursor.getString(idx);
cursor.close();
}
}
return path;

}

Ref: Get Real Path for Uri Android

getRealpathFromUri(Uri uri)
{
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
if (cursor == null) 
{ // Source is Dropbox or other similar local file path
result = contentURI.getPath();
}
else 
{ 
if(cursor.moveToFirst()){
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//String yourRealPath = cursor.getString(columnIndex);
path = cursor.getString(columnIndex);
}
cursor.close();
}
return path;
}

我使用以下代码从 Uri 获取文档的真实路径:

/**
* Retrieve filename from Uri
*
* @param uri             Uri following the schemes: "file" or "content"
* @param contentResolver ContentResolver to resolve content scheme
*
* @return filename if operation succeded. Can be null.
*/
public static String getFileName(@NonNull final Uri uri, @NonNull final ContentResolver contentResolver) {
String filename = "";
if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
filename = uri.getLastPathSegment();
} else if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
try {
Cursor cursor = contentResolver.query(uri, null, null, null, null);
int index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
cursor.moveToFirst();
filename = cursor.getString(index);
cursor.close();
} catch (Exception e) {
Log.e(TAG, "Exception when retrieving file name: " + e.getMessage());
}
}
return filename;
}

最新更新