繁体   English   中英

从图库中选择图像后从android URI获取真实路径

[英]get real path from android URI after selecting image from gallery

我(一个初学者 android)试图获取用户从图库中选择的图像的真实路径(例如:image_name.jpg 等)。

这是代码片段:

 if (requestCode == SELECT_FILE) {
        Uri selectedImage = data.getData();
        Bitmap bitmapImage;
        try {
              bitmapImage =decodeBitmap(selectedImage );
              photoImage = (ImageView) findViewById(R.id.photoImage);
              photoImage.setImageBitmap(bitmapImage);
              photoName = (TextView) findViewById(R.id.designPhoto);
              File thePath = new File(getRealPathFromURI(selectedImage));
              photoName.setText(getRealPathFromURI(selectedImage));
        } catch (Exception e) {
                e.printStackTrace();
        }
 }


 private String getRealPathFromURI(Uri contentURI) {

    String thePath = "no-path-found";
    String[] filePathColumn = {MediaStore.Images.Media.DATA};
    Cursor cursor = getContentResolver().query(contentURI, filePathColumn, null, null, null);
    if(cursor.moveToFirst()){
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        thePath = cursor.getString(columnIndex);
    }
    cursor.close();
    return  thePath;
}

但我在photoName没有得到任何东西也尝试了很多代码和指南,但没有成功。

但是当我尝试它时

photoName.setText(selectedImage.getPath()); 

我得到

/document/image:n (where n=any numbers) ex:/document/image:147 

但我想要一个正确的文件名或路径,例如: image_name.jpg/path/image_name.png

从过去 3 小时开始尝试,如果有人能帮助我,那就太好了。 谦虚 提前致谢。

我使用它工作

MediaStore.Images.Media.DISPLAY_NAME

更新和工作代码可能会帮助其他人:

private String getRealPathFromURI(Uri contentURI) {

    String thePath = "no-path-found";
    String[] filePathColumn = {MediaStore.Images.Media.DISPLAY_NAME};
    Cursor cursor = getContentResolver().query(contentURI, filePathColumn, null, null, null);
    if(cursor.moveToFirst()){
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        thePath = cursor.getString(columnIndex);
    }
    cursor.close();
    return  thePath;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM