我正在尝试从 Uri(从图库中选择的图像)获取真实路径,但此函数始终返回空值:
//Convert the image URI to the direct file system path of the image file
public String getRealPathFromURI(Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = getActivity().getContentResolver().query(contentUri, proj, null, null, null);
cursor.moveToFirst();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
最佳答案
那是因为您选择的图像在设备上实际不可用。
来自画廊或其他选择的图像可以来自不提供物理文件的不同来源,例如云存储。
在此处查看此代码,了解如何将 Uri
打开为 InputStream
,可用于创建文件副本(或直接读取)。
Android: Getting a file URI from a content URI?
编辑:
我正在对此做一些额外的研究,显然它也因如何你请求这个 Uri 而不同。
如果您这样请求(根据 Android 指南,这是当前的首选方法):
i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(i, REQUEST_STORAGE);
它会打开 KitKat 风格的 unified 选择器,如果您从那里选择图像,它将始终返回 null。如果您打开左侧抽屉菜单,选择图库(或文件浏览器),然后从那里选择一张图片,那么,如果它是本地文件图片,您将拥有正确的路径。
另一方面,如果您这样请求(这是旧方法):
i = new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivityForResult(i, REQUEST_STORAGE);
它会直接打开图库,同样,如果是本地文件图片,你会得到正确的路径。
是的,我仍然不相信有一种方法可以只强制本地化,但至少您有更多信息可以对您的编码做出明智的决定。
关于android - GetRealPathFromUri 总是得到空结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27113357/