为了账号安全,请及时绑定邮箱和手机立即绑定

android通过Uri.getPath()获取真实路径

android通过Uri.getPath()获取真实路径

android通过Uri.getPath()获取真实路径我正试图从画廊获取图像。Intent intent = new Intent();intent.setType("image/*");intent.setAction(Intent.ACTION_GET_CONTENT);startActivityForResult(Intent.createChooser(intent, "Select picture"), resultCode );从这个活动返回后,我有一个包含Uri的数据。看起来像:content://media/external/images/1如何将此路径转换为真实路径(就像' /sdcard/image.png')?谢谢
查看完整描述

3 回答

?
UYOU

TA贡献1878条经验 获得超4个赞

你真的有必要获得物理路径吗?
例如,ImageView.setImageURI()并且ContentResolver.openInputStream()允许你访问一个文件的内容,不知道它的真实路径。

查看完整回答
反对 回复 2019-08-06
?
慕哥9229398

TA贡献1877条经验 获得超6个赞

这就是我做的:

Uri selectedImageURI = data.getData();imageFile = new File(getRealPathFromURI(selectedImageURI));

和:

private String getRealPathFromURI(Uri contentURI) {
    String result;
    Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
    if (cursor == null) { // Source is Dropbox or other similar local file path
        result = contentURI.getPath();
    } else { 
        cursor.moveToFirst(); 
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
        result = cursor.getString(idx);
        cursor.close();
    }
    return result;}

注意:managedQuery()方法已弃用,因此我不使用它。

最后编辑:改进。我们应该关闭光标!!


查看完整回答
反对 回复 2019-08-06
  • 3 回答
  • 0 关注
  • 25661 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信