android 拍照到相册
时间: 2023-09-27 18:06:35 浏览: 43
要实现 Android 拍照并保存到相册,可以按照以下步骤进行:
1. 调用相机拍照。可以使用 Intent 调用系统相机,如下所示:
```
private void takePicture() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
```
2. 在 onActivityResult 方法中处理拍照结果。将拍照得到的图片保存到指定的文件路径中,再将其添加到相册中,如下所示:
```
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
String imageFilePath = saveImageToGallery(imageBitmap);
Toast.makeText(this, "Image saved to gallery: " + imageFilePath, Toast.LENGTH_SHORT).show();
}
}
private String saveImageToGallery(Bitmap bitmap) {
String fileName = "IMG_" + System.currentTimeMillis() + ".jpg";
File imageFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), fileName);
try {
FileOutputStream outputStream = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// Add the image to the gallery
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(imageFile);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
return imageFile.getAbsolutePath();
}
```
在这个方法中,首先将拍照得到的 Bitmap 对象保存到指定的文件路径中。然后,将该文件路径转换成 Uri 对象,再创建一个 Intent 对象,将该 Uri 对象设置为其属性值。最后,通过调用 sendBroadcast 方法将 Intent 发送给系统,让系统将该图片添加到相册中。
这样,就可以实现将拍照得到的图片保存到相册中了。