如何将文件Uri方案转换为内容Uri方案?

时间:2015-12-11 07:02:44

标签: android

在Android中,当您从图库中获取uri时,它的值将从content://blahblahblah.blahblah.format开始,但如果您从手机的相机获取uri,它将会启动与file:///

以下是我想要做的事情:

private File uriToBitmap(Uri uri, int maxSize) throws FileNotFoundException {
  try {
        imageStream = getContentResolver().openInputStream(uri);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    Bitmap claimBitmap = BitmapFactory.decodeStream(imageStream);
   }

在这个方法中我想传递文件类型uri并使用getContentResolver()函数,但遗憾的是claimBitmap是null,这是否意味着getContentResolver()方法不会接受文件输入uri?请帮忙。

2 个答案:

答案 0 :(得分:0)

关注此URL。它会帮助你 如果您存储在本地驱动器中。

    String filePath = null;
    Uri _uri = data.getData();
    Log.d("","URI = "+_uri);
    if(_uri!=null&&"content".equals(_uri.getScheme())){
    Cursor cursor=this.getContentResolver().query(_uri,new String[]{android.provider.MediaStore.Images.ImageColumns.DATA},null,null,null);
    cursor.moveToFirst();
    filePath=cursor.getString(0);
    cursor.close();
    }else
    {
    filePath=_uri.getPath();
    }

答案 1 :(得分:0)

不,ContentResolver支持文件方案,如果uri哪个方案不支持,此方法将抛出FileNotFoundException。请查看

public final InputStream openInputStream(Uri uri)
        throws FileNotFoundException {
    String scheme = uri.getScheme();
    if (SCHEME_ANDROID_RESOURCE.equals(scheme)) {
        // Note: left here to avoid breaking compatibility.  May be removed
        // with sufficient testing.
        OpenResourceIdResult r = getResourceId(uri);
        try {
            InputStream stream = r.r.openRawResource(r.id);
            return stream;
        } catch (Resources.NotFoundException ex) {
            throw new FileNotFoundException("Resource does not exist: " + uri);
        }
    } else if (SCHEME_FILE.equals(scheme)) {
        // Note: left here to avoid breaking compatibility.  May be removed
        // with sufficient testing.
        return new FileInputStream(uri.getPath());
    } else {
        AssetFileDescriptor fd = openAssetFileDescriptor(uri, "r", null);
        try {
            return fd != null ? fd.createInputStream() : null;
        } catch (IOException e) {
            throw new FileNotFoundException("Unable to create stream");
        }
    }
}

这是ContentResolver的源代码,希望这可以帮到你