Android studio调用相机并保存到相册
时间: 2023-03-02 07:01:27 浏览: 97
要在Android Studio中调用相机并保存到相册,您可以遵循以下步骤:
1. 在AndroidManifest.xml文件中添加相机和写入外部存储的权限:
```xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
2. 在布局文件中添加一个按钮或其他视图来触发相机操作:
```xml
<Button
android:id="@+id/btn_take_picture"
android:text="Take Picture" />
```
3. 在Activity中添加代码来处理相机操作:
```java
private static final int REQUEST_IMAGE_CAPTURE = 1;
private String currentPhotoPath;
// 创建保存图片的文件
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* 前缀 */
".jpg", /* 后缀 */
storageDir /* 存储目录 */
);
currentPhotoPath = image.getAbsolutePath();
return image;
}
// 调用相机
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// 创建保存图片的文件
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// 处理异常
}
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) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
// 图片保存成功后,将其添加到相册中
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
}
```
4. 在AndroidManifest.xml文件中添加FileProvider:
```xml
<application>
...
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.android.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>
```
5. 在res/xml目录下创建file_paths.xml文件:
```xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path name="my_images" path="Pictures" />
</paths>
```
现在,当用户点击“Take Picture”按钮时,将启动相机应用程序,