【问题标题】:Android - Get the path of the image user pick from galleryAndroid - 从图库中获取用户选择的图像路径
【发布时间】:2014-01-03 02:49:13
【问题描述】:

我正在开发一个安卓应用,当用户点击一个按钮时,应用会将用户带到图库中选择一张照片,然后返回应用显示照片。

这是我的onActivityResult回调函数的一部分:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if(requestCode == PICK_IMAGE && data != null && data.getData() != null) {

        Uri imageUri = data.getData();

        //User had pick an image.
        Cursor cursor = getContentResolver().query(imageUri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
        cursor.moveToFirst();

        //Link to the image
        final String imageFilePath = cursor.getString(0); 

        // imageFilePath is null

运行代码时,imageUri 包含一些内容提供程序 uri,例如 content:\\something,但是当我尝试获取图像的文件路径时,我得到了 null。

在这种情况下我应该如何检索用户选择的图像文件路径?

谢谢

【问题讨论】:

    标签: android


    【解决方案1】:

    这是我的代码,它的工作。

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

    你会得到 /sdcard/imagepath ..

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-29
      • 2015-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-18
      • 1970-01-01
      相关资源
      最近更新 更多