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。


  • 2017-04-15 23:56:30

    onInterceptTouchEvent和onTouchEvent调用关系详解

    如果没有onInterceptTouchEvent,只考虑onTouchEvent的话,比较容易分析和理解。假如有三层布局结构,linearLayout1,linearLayout2,textView,从前到后是包含的关系。那么下面分情况说明。

  • 2017-04-16 19:36:32

    ViewPager预加载问题和onCreateView多次调用问题的解决

    1,在使用ViewPager嵌套Fragment的时候,由于VIewPager的几个Adapter的设置来说,都会有一定的预加载(默认是左右各一个Frament)。通过设置setOffscreenPageLimit(int number) 来设置预加载的熟练,在V4包中,默认的预加载是1,即使你设置为0,也是不起作用的,设置的只能是大于1才会有效果的。我们需要通过更改V4包中的默认属性才可以

  • 2017-04-16 21:02:55

    ImageView的android:adjustViewBounds属性

    取值为true时: Adjust the ImageView's bounds to preserve the aspect ration of its drawable. 调整ImageView的界限来保持图像纵横比不变。 这并不意味着ImageView的纵横比就一定和图像的纵横比相同

  • 2017-04-18 17:12:50

    Laravel 读取 config 下的数据

    Laravel的config下一般存放配置信息,可以通过config('key')方法获取指定的数据。 设置值可通过「点」式语法读取,其中包含要访问的文件名以及选项名称。