我有一个onActivityResult从一个mediastore图像选择返回,我可以获得一个图像使用以下URI:
Uri selectedImage = data.getData();
将this转换为字符串会得到:
content://media/external/images/media/47
或路径给出:
/external/images/media/47
然而,我似乎找不到一种方法将其转换为绝对路径,因为我想将图像加载到位图中,而不必复制到某个地方。我知道这可以使用URI和内容解析器来完成,但这似乎在重新启动手机时中断,我猜MediaStore在重新启动之间没有保持其编号相同。
我是这样做的:
Uri queryUri = MediaStore.Files.getContentUri("external");
String columnData = MediaStore.Files.FileColumns.DATA;
String columnSize = MediaStore.Files.FileColumns.SIZE;
String[] projectionData = {MediaStore.Files.FileColumns.DATA};
String name = null;
String size = null;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if ((cursor != null)&&(cursor.getCount()>0)) {
int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
cursor.moveToFirst();
name = cursor.getString(nameIndex);
size = cursor.getString(sizeIndex);
cursor.close();
}
if ((name!=null)&&(size!=null)){
String selectionNS = columnData + " LIKE '%" + name + "' AND " +columnSize + "='" + size +"'";
Cursor cursorLike = getContentResolver().query(queryUri, projectionData, selectionNS, null, null);
if ((cursorLike != null)&&(cursorLike.getCount()>0)) {
cursorLike.moveToFirst();
int indexData = cursorLike.getColumnIndex(columnData);
if (cursorLike.getString(indexData) != null) {
result = cursorLike.getString(indexData);
}
cursorLike.close();
}
}
return result;
如果你的系统版本在19以上,这对我来说是完美的,希望这能帮助你。
@TargetApi(Build.VERSION_CODES.KITKAT)
public static String getPath(final Context context, final Uri uri) {
final boolean isOverKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isOverKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/"
+ split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"),
Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection,
selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
只是对第一个答案进行了简单的更新:mActivity.managedQuery()现在已弃用。我已经用新方法更新了代码。
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(mContext, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
Android开发源码
完美地为我修复了这篇文章的代码:
public static String getRealPathImageFromUri(Uri uri) {
String fileName =null;
if (uri.getScheme().equals("content")) {
try (Cursor cursor = MyApplication.getInstance().getContentResolver().query(uri, null, null, null, null)) {
if (cursor.moveToFirst()) {
fileName = cursor.getString(cursor.getColumnIndexOrThrow(ediaStore.Images.Media.DATA));
}
} catch (IllegalArgumentException e) {
Log.e(mTag, "Get path failed", e);
}
}
return fileName;
}
试试这个
不过,如果你想要得到真正的答案,你可以试试我的答案。以上答案对我没有帮助。
解释:-这个方法获取URI,然后检查你的Android设备的API级别,根据API级别,它将生成真实路径。生成真实路径方法的代码根据API级别不同而不同。
method to get the Real path from URI
@SuppressLint("ObsoleteSdkInt")
public String getPathFromURI(Uri uri){
String realPath="";
// SDK < API11
if (Build.VERSION.SDK_INT < 11) {
String[] proj = { MediaStore.Images.Media.DATA };
@SuppressLint("Recycle") Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
int column_index = 0;
String result="";
if (cursor != null) {
column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
realPath=cursor.getString(column_index);
}
}
// SDK >= 11 && SDK < 19
else if (Build.VERSION.SDK_INT < 19){
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader cursorLoader = new CursorLoader(this, uri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if(cursor != null){
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
realPath = cursor.getString(column_index);
}
}
// SDK > 19 (Android 4.4)
else{
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel, new String[]{ id }, null);
int columnIndex = 0;
if (cursor != null) {
columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
realPath = cursor.getString(columnIndex);
}
cursor.close();
}
}
return realPath;
}
Use this method like this
Log.e(TAG, "getRealPathFromURI: "+getPathFromURI(your_selected_uri) );
输出:
04-06 12:39:46,993 6138-6138/com。qtm E/tag: getrealthfro到处都是:
/存储/ emulated / 0 /视频/ avengers_infinity_war_4k_8k-7680x4320。jpg