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。


  • 2020-02-22 17:35:14

    使用tweenjs写一个发牌的demo

    移动端h5的三大抽奖方式:转盘,老虎机,翻纸牌。 前两样demo比较多,用户也审美疲劳了。这次微信公众号要抽奖,于是调研了下翻纸牌。

  • 2020-02-22 17:45:43

    tweenjs简单快速学习

    tweenjs 是使用 JavaScript 中的一个简单的补间动画库,支持数字、对象的属性和 CSS 样式属性的赋值。 tweenjs 以平滑的方式修改元素的属性值,需要传递给 tween 要修改的值、动画结束时的最终值和动画花费时间(duration),之后 tween 引擎就可以计算从开始动画点到结束动画点之间值,从而产生平滑的动画效果。

  • 2020-02-22 17:47:12

    easeJs入门学习教程

    createjs中包含以下四个部分: EaselJS:用于 Sprites、动画、向量和位图的绘制,创建 HTML5 Canvas 上的交互体验(包含多点触控) TweenJS:用于做动画效果 SoundJS:音频播放引擎 PreloadJS:网站资源预加载

  • 2020-02-22 17:54:59

    最新FullCalendar中文文档

    Fullcalendar是一款用来管理日程安排、工作计划的日历工具,它功能非常强大而且非常实用。而目前网络上没有很好的中文文档,为了更好的和大家分享Fullcalendar的相关使用,即日起计划将Fullcalendar的英文文档翻译成中文版。

  • 2020-02-22 17:57:05

    nuxtjs支持api接口,serverMiddleware

    Who can’t relate to this: You’ve built a small portfolio page for someone, maybe a company, a friend or yourself. And the only API endpoint you’d need is one for a form. What now? Scaffolding a new service just for this one endpoint?

  • 2020-02-22 17:59:34

    FullCalendar插件的基本使用带详细配置翻译

    前段时间,一直在开发考勤系统,当时为满足设计的需求,选了好几个插件,最后决定采用Fullcanlendar的插件。感觉这个插件可以满足现阶段的功能开发需求

  • 2020-02-22 18:03:10

    Vue组件中使用Sass或者Less全局变量

    本文以Sass做案例,Less的参考,基本配置大同小异。 假如我们有一个Sass的全局变量common.scss文件,路径 ../style/common.scss 代码如下: