Вы можете сохранить фотографии в каталоге изображений приложения следующим образом:
1. Создайте файл изображения:
private File createImageFile() throws IOException {
String timestamp = new SimpleDateFormat("yyyyMMdd_Hms").format(new Date());
String fileName = "JPEG_" + timestamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File photoImage = File.createTempFile(fileName, ".jpg", storageDir);
// Store this value in field to use later
picture1Path = photoImage.getAbsolutePath();
return photoImage;
}
Добавьте Uri файла изображения в намерение IMAGE_CAPTURE:
private void takePicture1() {
Intent imageTakeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
Log.e(MainActivity.class.getSimpleName(), e.getMessage(), e);
}
// Add file Uri to intent
if (photoFile != null) {
Uri photoUri = FileProvider.getUriForFile(
this,"com.your_app_package.fileprovider", photoFile);
imageTakeIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
}
if(imageTakeIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(imageTakeIntent,REQUEST_IMAGE_CAPTURE);
}
}
Сохранить Uri изображения к общим настройкам в случае успешного захвата изображения:
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE) {
if (resultCode == Activity.RESULT_OK) {
setPic();
// Save imageUri
preferences.edit().putString("image1Uri", currentPhotoPath).apply();
}
}
}
private void setPic() {
// load and display pic
Bitmap bitmap = BitmapFactory.decodeFile(currentPhotoPath);
imageView1.setImageBitmap(bitmap);
}
4. Затем настройте FileProvider:
В манифесте приложения. xml внутри тега:
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.your_app_package.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
Также включите WRITE_EXTERNAL_STORAGE разрешение.
Создайте «file_paths. xml» и добавьте:
<paths>
<external-files-path name="my_images" path="/"/>
</paths>
А затем в onCreate загрузите Uri файла изображения из настроек и отобразите:
currentPhotoPath = preferences.getString("image1Uri", null);
if (currentPhotoPath != null) {
setPic();
}