安卓调用系统相册拍照,并且怎么知道新照片的路径
时间: 2023-12-03 11:45:25 浏览: 77
可以使用以下代码来调用系统相机和相册,并获取拍摄照片的路径:
```java
// 调用系统相机拍照
private void takePhoto() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
File photoFile = createImageFile();
if (photoFile != null) {
Uri photoUri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);
}
}
}
// 调用系统相册选择照片
private void choosePhoto() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_CODE_CHOOSE_PHOTO);
}
// 创建照片文件
private File createImageFile() {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
try {
File imageFile = File.createTempFile(imageFileName, ".jpg", storageDir);
mCurrentPhotoPath = imageFile.getAbsolutePath();
return imageFile;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case REQUEST_CODE_TAKE_PHOTO:
// 拍照返回结果,mCurrentPhotoPath即为拍照照片的路径
handlePhoto(mCurrentPhotoPath);
break;
case REQUEST_CODE_CHOOSE_PHOTO:
// 相册选择照片返回结果,data.getData()即为选择的照片的路径
handlePhoto(getRealPathFromUri(data.getData()));
break;
}
}
}
// 获取URI对应的真实路径
private String getRealPathFromUri(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(columnIndex);
cursor.close();
return path;
}
return uri.getPath();
}
// 处理照片
private void handlePhoto(String photoPath) {
// 处理照片逻辑
}
```
在拍摄照片时,可以通过创建照片文件并在`Intent`中指定`MediaStore.EXTRA_OUTPUT`参数来保存拍摄的照片。在`onActivityResult`方法中,可以根据`requestCode`获取返回结果的类型,从而获取拍摄的照片的路径。在选择相册中的照片时,可以通过`getContentResolver().query()`方法获取照片的路径。
阅读全文