根据Uri获取文件的绝对路径

简易版处理(实际并没发现有什么问题)

public static String getRealPathFromURI(Context context, Uri contentURI) {
String result;
Cursor cursor = context.getContentResolver().query(contentURI,
new String[]{MediaStore.Images.ImageColumns.DATA},//
null, null, null);
if (cursor == null) result = contentURI.getPath();
else {
cursor.moveToFirst();
int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(index);
cursor.close();
}
return result;
}
 

复杂版处理

/**
* 根据图片的Uri获取图片的绝对路径(适配多种API)
*
* @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
*/
public static String getRealPathFromUri(Context context, Uri uri) {
int sdkVersion = Build.VERSION.SDK_INT;
if (sdkVersion < 11) return getRealPathFromUri_BelowApi11(context, uri);
if (sdkVersion < 19) return getRealPathFromUri_Api11To18(context, uri);
else return getRealPathFromUri_AboveApi19(context, uri);
}

/**
* 适配api19以上,根据uri获取图片的绝对路径
*/
@TargetApi(Build.VERSION_CODES.KITKAT)
private static String getRealPathFromUri_AboveApi19(Context context, Uri uri) {
String filePath = null;
String wholeID = DocumentsContract.getDocumentId(uri);

// 使用':'分割
String id = wholeID.split(":")[1];

String[] projection = {MediaStore.Images.Media.DATA};
String selection = MediaStore.Images.Media._ID + "=?";
String[] selectionArgs = {id};

Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,//
projection, selection, selectionArgs, null);
int columnIndex = cursor.getColumnIndex(projection[0]);
if (cursor.moveToFirst()) filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
}

/**
* 适配api11-api18,根据uri获取图片的绝对路径
*/
private static String getRealPathFromUri_Api11To18(Context context, Uri uri) {
String filePath = null;
String[] projection = {MediaStore.Images.Media.DATA};
CursorLoader loader = new CursorLoader(context, uri, projection, null, null, null);
Cursor cursor = loader.loadInBackground();

if (cursor != null) {
cursor.moveToFirst();
filePath = cursor.getString(cursor.getColumnIndex(projection[0]));
cursor.close();
}
return filePath;
}

/**
* 适配api11以下(不包括api11),根据uri获取图片的绝对路径
*/
private static String getRealPathFromUri_BelowApi11(Context context, Uri uri) {
String filePath = null;
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
filePath = cursor.getString(cursor.getColumnIndex(projection[0]));
cursor.close();
}
return filePath;
}
 
posted @ 2018-02-06 02:26  牧之丨  阅读(2894)  评论(0编辑  收藏  举报