Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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


2 Answers

according to the latest updates for android R (API level 30) and Android storage use cases and best practices, you might use the code below to save your image in your app's cache storage

File file = new File(getContext().getExternalCacheDir() + File.separator + System.currentTimeMillis() + ".png");
like image 51
Amir jodat Avatar answered Sep 22 '25 16:09

Amir jodat


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.

like image 38
CommonsWare Avatar answered Sep 22 '25 15:09

CommonsWare