【问题标题】:How can I convert a file Uri scheme into content Uri scheme?如何将文件 Uri 方案转换为内容 Uri 方案?
【发布时间】:2015-12-11 15:22:43
【问题描述】:

在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?请帮忙。

【问题讨论】:

    标签: android


    【解决方案1】:

    不,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的源码,希望对你有帮助

    【讨论】:

    • 那么我怎样才能简单地将文件 uri 方案转换为位图?
    【解决方案2】:

    关注这个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();
        }
    

    【讨论】:

    • 这应该是一条评论
    猜你喜欢
    • 2021-04-30
    • 2011-11-10
    • 1970-01-01
    • 2014-08-13
    • 2012-08-15
    • 2011-02-20
    • 2023-04-06
    • 2021-06-12
    • 2011-06-25
    相关资源
    最近更新 更多