Android中Uri和Path之间的转换

2017-12-24 12:04:40

今天选择,剪裁,上传图片,用到了Uri。出现了错误。

原来Uri分好多种。

今天知道了就两种,

Media Uri

File Uri 



1. 从URI中获取真实文件路径

[java] view plain copy

  1. private String uriToRealPath(Uri uri) {  

  2.     Cursor cursor = managedQuery(uri,  

  3.             new String[] {MediaStore.Images.Media.DATA},  

  4.             null,  

  5.             null,  

  6.             null);  

  7.     cursor.moveToFirst();  

  8.     String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));  

  9.     return path;  

  10. }  


2. 从真实路径转换为文件URI


[java] view plain copy

  1. Uri uri = Uri.fromFile(new File(filePath));  


3. 从真实路径转换为媒体库URI


[java] view plain copy

  1. private Uri pathToMediaUri(String path) {  

  2.     Uri mediaUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;  

  3.       

  4.     Cursor cursor = getContentResolver().query(mediaUri,  

  5.             null,  

  6.             MediaStore.Images.Media.DISPLAY_NAME + "=" + path.substring(path.lastIndexOf("/") + 1),  

  7.             null,  

  8.             null);  

  9.     cursor.moveToFirst();  

  10.       

  11.     Uri uri = ContentUris.withAppendedId(mediaUri, cursor.getLong(0));  

  12.     return uri;  

  13. }  

  PS: 如果想调用"com.android.camera.action.CROP"裁剪图片,文件URI是用不了的,必须要获取媒体库的URI。


  • 2018-10-30 00:16:41

    android ToolBar 设置颜色

    app:popupTheme——有时候我们有需求:ActionBar文字是白的,ActionBar Overflow弹出的是白底黑字让ActionBar文字是白的,那么对应的theme肯定是Dark。可是让ActionBar弹出的是白底黑字,那么需要Light主题。这时候popupTheme就派上用场了。android:theme 与app:theme——在AppCompat v21里,提供了一个快速方便的方法设置Toolbar的主题,使用app:theme。而新版本22.1.x中,AppCompat 允许对 Toolbar 使用 android:theme代替 app:theme。最好的一点是:它会自动继承父视图的theme ,并且兼容所有APIv11以上的设备。

  • 2018-11-01 22:08:19

    Android Toolbar左、中、右对齐

    默认的Android Toolbar中添加子元素view是从左到右依次添加。需要注意的是,Android Toolbar为自身的NavigationIcon(app:navigationIcon)最靠右,Logo(app:logo)紧接NavigationIcon、Title(app:title)接续Logo、保留了默认的位置(从左边到右)。这些Android Toolbar保留的系统设置字段将挤压开发者自己安放在Toolbar中的子view,如图所示:

  • 2018-11-06 06:42:59

    XUtils3框架数据库的基本使用方法

    今天给大家带来数据库模块的讲解,现在主流的ORM框架很多,比如OrmLite,GreenDao,Active Android,Realm等等,这些框架每个都有自己的优点和缺点,大家完全可以根据自己项目的实际需求进行选择,下面开始进入今天的数据库模块的介绍。