调用系统相机进行拍照,并且获取照片路径的完整代码
时间: 2023-12-03 22:46:39 浏览: 95
以下是 Android 平台上调用系统相机进行拍照并获取照片路径的完整代码:
```java
private static final int REQUEST_IMAGE_CAPTURE = 1;
private String currentPhotoPath;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Image saved to " + currentPhotoPath, Toast.LENGTH_LONG).show();
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
```
在上面的代码中,我们首先调用 `dispatchTakePictureIntent()` 方法来启动系统相机应用。在此方法中,我们将 `MediaStore.ACTION_IMAGE_CAPTURE` 作为参数传递给 `Intent` 对象,该参数告诉系统我们要启动相机应用并拍摄照片。
然后,我们检查是否有可处理此 Intent 的相机应用程序。如果有,我们使用 `createImageFile()` 方法创建一个临时文件来保存照片,并在 `photoURI` 中存储该文件的 URI。然后,我们将 `photoURI` 作为参数传递给 `takePictureIntent.putExtra()` 方法,以便系统相机应用程序可以将拍摄到的照片保存到该文件中。
当用户拍摄照片并保存到指定文件后,系统会将 `RESULT_OK` 一起返回,我们可以在 `onActivityResult()` 方法中通过检查 `requestCode` 和 `resultCode` 来确定是否成功拍摄照片。如果成功拍摄照片,我们可以在 `currentPhotoPath` 变量中获取照片的完整路径。
阅读全文