我有一个onActivityResult从一个mediastore图像选择返回,我可以获得一个图像使用以下URI:
Uri selectedImage = data.getData();
将this转换为字符串会得到:
content://media/external/images/media/47
或路径给出:
/external/images/media/47
然而,我似乎找不到一种方法将其转换为绝对路径,因为我想将图像加载到位图中,而不必复制到某个地方。我知道这可以使用URI和内容解析器来完成,但这似乎在重新启动手机时中断,我猜MediaStore在重新启动之间没有保持其编号相同。
完美地为我修复了这篇文章的代码:
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;
}
API 19及以上,图像文件路径从Uri工作完美。我还检查了最新的PIE API 28。
public String getImageFilePath(Uri uri) {
String path = null, image_id = null;
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
image_id = cursor.getString(0);
image_id = image_id.substring(image_id.lastIndexOf(":") + 1);
cursor.close();
}
cursor = getContentResolver().query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Media._ID + " = ? ", new String[]{image_id}, null);
if (cursor!=null) {
cursor.moveToFirst();
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
}
return path;
}
从图库中获取图像后,只需要在下面的方法中传递URI,仅适用于Android 4.4 (KitKat):
public String getPath(Uri contentUri) {// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(contentUri);
// 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);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}