使用以下方法从 Uri 中获取文件路径。在这里,您需要传递上下文和 uri,它保持与前 Kitkat 的兼容性。
public String getRealPathFromURI(Context context, Uri contentUri) {
String res = "";
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
} else {
Log.d(TAG, "Cursor is null");
return contentUri.getPath();
}
return res;
}
已针对相机更新:上述解决方案适用于为 Gallery Intent 返回的 Uri。对于相机意图,请使用以下代码。
public File getOutputMediaFile() {
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir;
// If the externam directory is writable then then return the External
// pictures directory.
if (isExternalStorageWritable()) {
mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
.getAbsolutePath() + File.separator + IConstants.CUSTOM_PROFILE_PIC_PATH);
} else {
mediaStorageDir = Environment.getDownloadCacheDirectory();
}
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
创建一个全局变量selectedImage用于存储图片路径。
private Uri getOutputMediaFileUri() {
File mediaFile = Utilities.getInstance().getOutputMediaFile();
selectedImage = mediaFile.getAbsolutePath();
return Uri.fromFile(mediaFile);
}
现在使用以下方法调用相机意图。
public void dispatchCameraIntent(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// If there any applications that can handle this intent then call the intent.
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
Uri fileUri = getOutputMediaFileUri();
Log.d(TAG, "camera Uri : " + fileUri);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(takePictureIntent, CAMERA_PICKER);
}
}
在OnActivityResult 中使用selectedImage 作为文件路径。