Android studio拍照保存到系统相册
时间: 2023-12-21 10:04:03 浏览: 86
您好!感谢您使用ChitGPT与我进行对话。关于您的问题,Android Studio拍照保存到系统相册的操作步骤如下:
1. 在manifest文件中添加相机和存储权限:
```
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
```
2. 创建一个用于保存图片的文件,示例代码如下:
```
File photoFile = null;
try {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
photoFile = File.createTempFile(
imageFileName,
".jpg",
storageDir
);
} catch (IOException ex) {
Log.e(TAG, ex.getMessage(), ex);
}
```
3. 启动相机并拍照,示例代码如下:
```
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
```
4. 在onActivityResult方法中处理拍照结果并将图片保存到系统相册,示例代码如下:
```
@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);
}
}
```
希望能够帮到您!如果还有其他问题,请继续问我。
阅读全文