在Android应用程序中拍照并保存到图库中,涉及到以下几个基础概念和技术点:
以下是一个简单的示例代码,展示如何在Android应用程序中拍照并保存到图库中:
在AndroidManifest.xml
中添加必要的权限:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" android:required="true" />
private static final int REQUEST_IMAGE_CAPTURE = 1;
private Uri imageUri;
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) {
// Error occurred while creating the File
}
if (photoFile != null) {
imageUri = FileProvider.getUriForFile(this, "com.example.android.fileprovider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
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);
return image;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
// 图片已保存到imageUri指定的位置
// 可以通过MediaStore API将图片添加到图库
MediaScannerConnection.scanFile(this, new String[]{imageUri.getPath()}, null, null);
}
}
AndroidManifest.xml
中正确配置FileProvider,并在res/xml
目录下创建file_paths.xml
文件。通过以上步骤,你可以在Android应用程序中实现拍照并保存到图库的功能。
领取专属 10元无门槛券
手把手带您无忧上云