从 mediastore 的 URI 中获取文件名和路径 [英] Get filename and path from URI from mediastore
问题描述
我有一个 onActivityResult
从媒体存储图像选择返回,我可以使用以下方法获取图像的 URI:
I have an onActivityResult
returning from an mediastore image selection which I can get a URI for an image using the following:
Uri selectedImage = data.getData();
将其转换为字符串给出:
Converting this to a string gives this:
content://media/external/images/media/47
或者给一个路径:
/external/images/media/47
但是我似乎无法找到将其转换为绝对路径的方法,因为我想将图像加载到位图中而不必将其复制到某处.我知道这可以使用 URI 和内容解析器来完成,但这似乎在手机重启时中断,我猜 MediaStore
在重启之间不会保持其编号相同.
However I can't seem to find a way to convert this into an absolute path, as I want to load the image into a bitmap without having to copy it somewhere. I know this can be done using the URI and content resolver, but this seems to break on rebooting of the phone, I guess MediaStore
doesn't keep its numbering the same between reboots.
推荐答案
Below API 19 使用此代码从 URI 获取文件路径:
Below API 19 use this code to get File Path from URI:
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
这篇关于从 mediastore 的 URI 中获取文件名和路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!