一个android文件的Uri地址一般如下:

content://media/external/images/media/62026

这是一张图片的Uri,那么我们如何根据这个Uri获得其在文件系统中的路径呢?

其实很简单,直接上代码:

/**
* Try to return the absolute file path from the given Uri
*
* @param context
* @param uri
* @return the file path or null
*/
public static String getRealFilePath( final Context context, final Uri uri ) {
if ( null == uri ) return null;
final String scheme = uri.getScheme();
String data = null;
if ( scheme == null )
data = uri.getPath();
else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
data = uri.getPath();
} else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
Cursor cursor = context.getContentResolver().query( uri, new String[] { ImageColumns.DATA }, null, null, null );
if ( null != cursor ) {
if ( cursor.moveToFirst() ) {
int index = cursor.getColumnIndex( ImageColumns.DATA );
if ( index > - ) {
data = cursor.getString( index );
}
}
cursor.close();
}
}
return data;
}

那么假如我们有一个图片的路径地址又该如何获得其Uri呢?

    String type = Utils.ensureNotNull(intent.getType());
Log.d(TAG, "uri is " + uri);
if (uri.getScheme().equals("file") && (type.contains("image/"))) {
String path = uri.getEncodedPath();
Log.d(TAG, "path1 is " + path);
if (path != null) {
path = Uri.decode(path);
Log.d(TAG, "path2 is " + path);
ContentResolver cr = this.getContentResolver();
StringBuffer buff = new StringBuffer();
buff.append("(")
.append(Images.ImageColumns.DATA)
.append("=")
.append("'" + path + "'")
.append(")");
Cursor cur = cr.query(
Images.Media.EXTERNAL_CONTENT_URI,
new String[] { Images.ImageColumns._ID },
buff.toString(), null, null);
int index = ;
for (cur.moveToFirst(); !cur.isAfterLast(); cur
.moveToNext()) {
index = cur.getColumnIndex(Images.ImageColumns._ID);
// set _id value
index = cur.getInt(index);
}
if (index == ) {
//do nothing
} else {
Uri uri_temp = Uri
.parse("content://media/external/images/media/"
+ index);
Log.d(TAG, "uri_temp is " + uri_temp);
if (uri_temp != null) {
uri = uri_temp;
}
}
}
}

最新文章

  1. 使用excel计算指数平滑和移动平均
  2. WPF(WP7、WP8)多个Listbox嵌套时滚动问题的解决
  3. Java语言中几个常用的包
  4. JavaScript实现li隔行变色
  5. SQL injection
  6. HTML的<body>标签详解与HTML常用的控制标记
  7. 【HDOJ】3828 A + B problem
  8. vue 全局插槽 全局插座
  9. 如何实现dede首页栏目文章指定调用
  10. unity 使用方法
  11. ubuntu nginx ssl 证书配置
  12. 测者的测试技术笔记:Screenplay 模式(Journey 模式)
  13. Jetpack 迁移到 androidX support MD
  14. python基础学习笔记(五)
  15. bzoj 4184: shallot (线段树维护线性基)
  16. Java如何将每个单词的第一个字符转为大写?
  17. xcode工程编译错误:The maximum number of apps for free development profiles has been reached.
  18. 前端web的图标的样式
  19. Win10开发环境配置
  20. 使用layui 和 jquery 问题小结

热门文章

  1. 紫书 例题 9-3 UVa 1347 ( 状态设计)
  2. oracle基础入门(一)
  3. IntelliJ IDEA 详细图解最常用的配置 ,适合刚刚用的新人。(转)
  4. JavaLearning:日期操作类
  5. #学习笔记#——JavaScript 数组部分编程(一)
  6. Vectorized implementation
  7. HDU 2564 饭卡
  8. Spark 1.6.1 源码分析
  9. java(面向对象 )
  10. 关于css的入门知识