在系统相机中拍照,获取照片文件的路径,完整代码
时间: 2023-11-03 19:05:35 浏览: 155
以下是一个获取相机拍摄照片路径的完整代码示例,你可以在你的Android应用程序中使用它:
```java
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_IMAGE_CAPTURE = 1;
private String currentPhotoPath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button takePictureButton = findViewById(R.id.button_image);
takePictureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
}
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) {
// Photo captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Image saved to:\n" + currentPhotoPath, Toast.LENGTH_LONG).show();
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").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;
}
}
```
上述代码中,我们使用了系统相机应用程序拍摄照片,并将其保存到文件中。在 `createImageFile()` 方法中,我们创建了一个文件名,使用 `File.createTempFile()` 方法创建了一个临时文件,并将其路径存储在 `currentPhotoPath` 变量中。然后,在 `dispatchTakePictureIntent()` 方法中,我们使用 `FileProvider` 来生成一个 `content://` URI,以便在 Android 7.0 及更高版本的设备上共享文件。最后,在 `onActivityResult()` 方法中,我们可以使用 `currentPhotoPath` 变量来获取拍摄的图片文件的路径。
阅读全文