1 /** 2 * 通过Uri返回File文件 3 * 注意:通过相机的是类似content://media/external/images/media/97596 4 * 通过相册选择的:file:///storage/sdcard0/DCIM/Camera/IMG_20150423_161955.jpg 5 * 通过查询获取实际的地址 6 * @param uri 7 * @return 8 */ 9 public File getFileByUri(Uri uri) { 10 String path = null; 11 if ("file".equals(uri.getScheme())) { 12 path = uri.getEncodedPath(); 13 if (path != null) { 14 path = Uri.decode(path); 15 ContentResolver cr = activity.getContentResolver(); 16 StringBuffer buff = new StringBuffer(); 17 buff.append("(").append(Images.ImageColumns.DATA).append("=").append("'" + path + "'").append(")"); 18 Cursor cur = cr.query(Images.Media.EXTERNAL_CONTENT_URI, new String[] { Images.ImageColumns._ID, Images.ImageColumns.DATA }, buff.toString(), null, null); 19 int index = 0; 20 int dataIdx = 0; 21 for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) { 22 index = cur.getColumnIndex(Images.ImageColumns._ID); 23 index = cur.getInt(index); 24 dataIdx = cur.getColumnIndex(Images.ImageColumns.DATA); 25 path = cur.getString(dataIdx); 26 } 27 cur.close(); 28 if (index == 0) { 29 } else { 30 Uri u = Uri.parse("content://media/external/images/media/" + index); 31 System.out.println("temp uri is :" + u); 32 } 33 } 34 if (path != null) { 35 return new File(path); 36 } 37 } else if ("content".equals(uri.getScheme())) { 38 // 4.2.2以后 39 String[] proj = { MediaStore.Images.Media.DATA }; 40 Cursor cursor = activity.getContentResolver().query(uri, proj, null, null, null); 41 if (cursor.moveToFirst()) { 42 int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 43 path = cursor.getString(columnIndex); 44 } 45 cursor.close(); 46 47 return new File(path); 48 } else { 49 Log.i(TAG, "Uri Scheme:" + uri.getScheme()); 50 } 51 return null; 52 }