从DocumentUI获取图片正确姿势

来源:互联网 发布:淘宝店铺资质认证 编辑:程序博客网 时间:2024/05/01 12:05

1 请求打开DocumentUI
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(“* / *”);
startActivityForResult(intent, REQUEST);
2 获取DocumentUI返回的uri
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//获取图片路径
if (requestCode == REQUEST && resultCode == Activity.RESULT_OK && data != null) {
String path = getPath(this, data.getData()).getPath();
Log.d(“ndh–”, “path=” + path);
showImage(path);
}
}
3 解析获取到的uri
由于从内部存储取得的图片uri格式为:
content://com.android.externalstorage.documents/document/primary:Download/Email/20170223_153857-2-2.jpg
从google photo取得的图片uri格式为:
content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Ffile%2F193/ORIGINAL/NONE/309151793
这两种uri格式只是表明了图片的存放位置,并非真实的图片文件的uri,因此无法直接加载 。
要想获得真实图片地址uri需要再次解析相应数据库:
// 以下代码为网络搜集整理

private static String getPath(Context context, Uri uri) {        if(null == uri || context == null){            return null;        }        // DocumentProvider        if (DocumentsContract.isDocumentUri(context, uri)) {            // ExternalStorageProvider            if (isExternalStorageDocument(uri)) {                return getExternalStroageDocumentPath(uri);            }            // DownloadsProvider            else if (isDownloadsDocument(uri)) {                return getDownloadsDocumentPath(context, uri);            }            // MediaProvider            else if (isMediaDocument(uri)) {                return getMediaDocumentPath(context, uri);            }        }        // MediaStore (and general)        else if ("content".equalsIgnoreCase(uri.getScheme())) {            // Return the remote address            if (isGooglePhotosUri(uri))                return uri.getLastPathSegment();            return getDataColumn(context, uri, null, null);        }        // File        else if ("file".equalsIgnoreCase(uri.getScheme())) {            return uri.getPath();        }        return uri.getPath();    }    private static String getDownloadsDocumentPath(Context context, Uri uri) {        String id = DocumentsContract.getDocumentId(uri);        Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));        return getDataColumn(context, contentUri, null, null);    }    private static String getMediaDocumentPath(Context context, Uri uri) {        String docId = DocumentsContract.getDocumentId(uri);        if(null == docId ){            return null;        }        String[] split = docId.split(":");        if(null == split || split.length<2){            return null;        }        String type = split[0];        Uri contentUri = null;        if ("image".equals(type)) {            contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;        } else if ("video".equals(type)) {            contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;        } else if ("audio".equals(type)) {            contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;        }        String selection = "_id=?";        String[] selectionArgs = new String[]{split[1]};        return getDataColumn(context, contentUri, selection, selectionArgs);    }    private static String getExternalStroageDocumentPath(Uri uri) {        String docId = DocumentsContract.getDocumentId(uri);        if(null == docId){            return null;        }        String[] split = docId.split(":");        if(null == split || split.length<2){            return null;        }        String type = split[0];        if ("primary".equalsIgnoreCase(type)) {            //内置存储            return Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + split[1];        } else {            //外置sd卡            String path = System.getenv("SECONDARY_STORAGE") + "/" + split[1];            return path;        }    }    /**     * Get the value of the data column for this Uri. This is useful for     * MediaStore Uris, and other file-based ContentProviders.     *     * @param context       The context.     * @param uri           The Uri to query.     * @param selection     (Optional) Filter used in the query.     * @param selectionArgs (Optional) Selection arguments used in the query.     * @return The value of the _data column, which is typically a file path.     */    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {        String column = "_data";        String[] projection = {column};        try (Cursor cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null)) {            if (cursor != null && cursor.moveToFirst()) {                int index = cursor.getColumnIndexOrThrow(column);                return cursor.getString(index);            }        }        return null;    }    /**     * @param uri The Uri to check.     * @return Whether the Uri authority is ExternalStorageProvider.     */    private static boolean isExternalStorageDocument(Uri uri) {        return "com.android.externalstorage.documents".equals(uri.getAuthority());    }    /**     * @param uri The Uri to check.     * @return Whether the Uri authority is DownloadsProvider.     */    private static boolean isDownloadsDocument(Uri uri) {        return "com.android.providers.downloads.documents".equals(uri.getAuthority());    }    /**     * @param uri The Uri to check.     * @return Whether the Uri authority is MediaProvider.     */    private static boolean isMediaDocument(Uri uri) {        return "com.android.providers.media.documents".equals(uri.getAuthority());    }    /**     * @param uri The Uri to check.     * @return Whether the Uri authority is Google Photos.     */    private static boolean isGooglePhotosUri(Uri uri) {        return "com.google.android.apps.photos.content".equals(uri.getAuthority());    }
0 0
原创粉丝点击