android – Why does MediaStore.Images.Media.insertImage always save images in the Pictures folder?-ThrowExceptions

Exception or error:

I would like to save my images in a folder that corresponds to the name of my app, instead of the default “Pictures” folder. Here’s my code in onRequestPermissionsResult:

if(requestCode == SAVE_IMAGE) {
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                try {
                    String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + R.string.app_name + "/";
                    File dir = new File(path);

                    OutputStream out;
                    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

                    File photoFile = new File(path, timeStamp + ".jpg");

                    out = new FileOutputStream(photoFile);

                    Bitmap full_image_result = full_image.copy(full_image.getConfig(), true);
                    full_image_result.compress(Bitmap.CompressFormat.JPEG, 90, out);

                    MediaStore.Images.Media.insertImage(MainActivity.this.getContentResolver(),photoFile.getAbsolutePath(), photoFile.getName(), photoFile.getName());


                    Toast.makeText(getApplicationContext(),R.string.savedMessage, Toast.LENGTH_LONG).show();

                } catch (IOException e) {
            } else {
                Toast.makeText(getApplicationContext(), R.string.noPermissions, Toast.LENGTH_LONG).show();
How to solve:

Somehow the path was wrong, replaced it with Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictura/" and now it’s working. I also replaced the insertImage call with

MediaScannerConnection.scanFile(this, new String[]{photoFile.getAbsolutePath()}, new String[]{"image/jpg"}, null);

, as CommonsWare suggested.

Leave a Reply

Your email address will not be published. Required fields are marked *