(1条消息) 解决android4.4以上系统的相册选择图片后获取不到有效的URI
最近用到上传图片发现,当选择相册里的照片时,会出现无效的URI,android4.4以上系统,选择相册中的最近照片,也会报同样的错误。
找到如下两个方法:
方法一:
/** * 图片选择及拍照结果 */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != RESULT_OK) { return; } Uri uri = null; switch (requestCode) { case PHOTOZOOM:// 相册 if (data == null) { return; } uri = data.getData(); String[] proj = {MediaStore.Images.Media.DATA}; Cursor cursor = managedQuery(uri, proj, null, null, null); int column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); path = cursor.getString(column_index);// 图片在的路径 Intent intent3 = new Intent(mContext, UserRectClipHead.class); intent3.putExtra("path", path); Log.i("选择图片路径",path+""); startActivityForResult(intent3, IMAGE_COMPLETE); break; case PHOTOTAKE:// 拍照 path = photoSavePath + photoSaveName; uri = Uri.fromFile(new File(path)); Intent intent2 = new Intent(mContext, UserRectClipHead.class); intent2.putExtra("path", path); startActivityForResult(intent2, IMAGE_COMPLETE); break; case IMAGE_COMPLETE: final String temppath = data.getStringExtra("path"); Intent intent = new Intent(); saveAllPath = FileUtils.saveBitmap(compressImage(BitmapUtils.UrlToBitmap(temppath)), ((int) (Math.random() * 10000)) + ".png");//质量压缩并存储得到path intent.putExtra("path", saveAllPath); // intent.putExtra("path", temppath); setResult(0, intent); try { cbuilder = new CustomDialogLoading.Builder(mContext, "上传中..."); mDialog = cbuilder.create(); mDialog.show(); postFile(saveAllPath); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } add_img.setImageBitmap(BitmapUtils.UrlToBitmap(temppath)); break; default: break; } super.onActivityResult(requestCode, resultCode, data); }
发现有些手机获取不到图片的path,后来经查找发现是因为android4.4以上的手机相册中有个最近的照片,是获取不到path路径的,更改如下可以解决:
/** * 图片选择及拍照结果 */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != RESULT_OK) { return; } Uri uri = null; switch (requestCode) { case PHOTOZOOM:// 相册 if (data == null) { return; } uri = data.getData(); //此处为了解决android4.4 相册选择时的 选择最近图片 获取不到path问题 if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT){//4.4及以上 String wholeID = DocumentsContract.getDocumentId(uri); String id = wholeID.split(":")[1]; String[] column = { MediaStore.Images.Media.DATA }; String sel = MediaStore.Images.Media._ID + "=?"; Cursor cursor = this.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel, new String[] { id }, null); int columnIndex = cursor.getColumnIndex(column[0]); if (cursor.moveToFirst()) { path = cursor.getString(columnIndex); } cursor.close(); }else{//4.4以下,即4.4以上获取路径的方法 String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = this.getContentResolver().query(uri, projection, null, null, null); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); path = cursor.getString(column_index); } // } Intent intent3 = new Intent(mContext, UserRectClipHead.class); intent3.putExtra("path", path); Log.i("x选择图片",path+""); startActivityForResult(intent3, IMAGE_COMPLETE); break; case PHOTOTAKE:// 拍照 path = photoSavePath + photoSaveName; uri = Uri.fromFile(new File(path)); Intent intent2 = new Intent(mContext, UserRectClipHead.class); intent2.putExtra("path", path); startActivityForResult(intent2, IMAGE_COMPLETE); break; case IMAGE_COMPLETE: final String temppath = data.getStringExtra("path"); Intent intent = new Intent(); saveAllPath = FileUtils.saveBitmap(compressImage(BitmapUtils.UrlToBitmap(temppath)), ((int) (Math.random() * 10000)) + ".png");//质量压缩并存储得到path intent.putExtra("path", saveAllPath); // intent.putExtra("path", temppath); setResult(0, intent); try { cbuilder = new CustomDialogLoading.Builder(mContext, "上传中..."); mDialog = cbuilder.create(); mDialog.show(); postFile(saveAllPath); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } add_img.setImageBitmap(BitmapUtils.UrlToBitmap(temppath)); break; default: break; } super.onActivityResult(requestCode, resultCode, data); }
方法二:
- /**
- * 根据Uri获取图片绝对路径,解决Android4.4以上版本Uri转换
- * @param activity
- * @param imageUri
- * @author yaoxing
- * @date 2014-10-12
- */
- @TargetApi(19)
- public static String getImageAbsolutePath(Activity context, Uri imageUri) {
- if (context == null || imageUri == null)
- return null;
- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, imageUri)) {
- if (isExternalStorageDocument(imageUri)) {
- String docId = DocumentsContract.getDocumentId(imageUri);
- String[] split = docId.split(":");
- String type = split[0];
- if ("primary".equalsIgnoreCase(type)) {
- return Environment.getExternalStorageDirectory() + "/" + split[1];
- }
- } else if (isDownloadsDocument(imageUri)) {
- String id = DocumentsContract.getDocumentId(imageUri);
- Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
- return getDataColumn(context, contentUri, null, null);
- } else if (isMediaDocument(imageUri)) {
- String docId = DocumentsContract.getDocumentId(imageUri);
- String[] split = docId.split(":");
- 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 = MediaStore.Images.Media._ID + "=?";
- String[] selectionArgs = new String[] { split[1] };
- return getDataColumn(context, contentUri, selection, selectionArgs);
- }
- } // MediaStore (and general)
- else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
- // Return the remote address
- if (isGooglePhotosUri(imageUri))
- return imageUri.getLastPathSegment();
- return getDataColumn(context, imageUri, null, null);
- }
- // File
- else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
- return imageUri.getPath();
- }
- return null;
- }
- public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
- Cursor cursor = null;
- String column = MediaStore.Images.Media.DATA;
- String[] projection = { column };
- try {
- cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
- if (cursor != null && cursor.moveToFirst()) {
- int index = cursor.getColumnIndexOrThrow(column);
- return cursor.getString(index);
- }
- } finally {
- if (cursor != null)
- cursor.close();
- }
- return null;
- }
- /**
- * @param uri The Uri to check.
- * @return Whether the Uri authority is ExternalStorageProvider.
- */
- public 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.
- */
- public 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.
- */
- public 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.
- */
- public static boolean isGooglePhotosUri(Uri uri) {
- return "com.google.android.apps.photos.content".equals(uri.getAuthority());
- }
赞 (0)