Skip to content
Advertisement

Set CameraX image capture File path

I set the File path to the following:

File file = new File(Environment.getExternalStorageDirectory() + "/" + System.currentTimeMillis() + ".png");

    ImageCapture.OutputFileOptions outputFileOptions =
            new ImageCapture.OutputFileOptions.Builder(file).build();

    imageCapture.takePicture(outputFileOptions, Executors.newSingleThreadExecutor(),
            new ImageCapture.OnImageSavedCallback() {
                @Override
                public void onImageSaved(ImageCapture.OutputFileResults outputFileResults) {
                    // insert your code here.
                    Log.d("PHOTO", "onImageSaved: saved");
                }
                @Override
                public void onError(ImageCaptureException error) {
                    // insert your code here.
                    Log.d("PHOTO", "onError: " + error);

                }
            });

But for some reason when i click on the capture image button, it jumps into the onError and logs the following:

onError: androidx.camera.core.ImageCaptureException: Failed to write or close the file

Advertisement

Answer

Your app needs permission to write to the desired location.

You could request WRITE_EXTERNAL_STORAGE, both in the manifest and at runtime, to allow you to write where you requested… up through Android 9. Android 10 and beyond do not support ordinary apps creating arbitrary directories in the root of external storage.

Your choice of getExternalFilesDir() means that you do not need any permissions. The downside is that the file(s) that you put there get removed when your app is uninstalled.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement