23

I am using this code to save Bitmap in External Storage but it does not create the folder if it not exists:

String path = Environment.getExternalStorageDirectory().toString();
        OutputStream fOutputStream = null;
        File file = new File(path + "/Captures/", "screen.jpg");
        try {
            fOutputStream = new FileOutputStream(file);

            capturedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOutputStream);

            fOutputStream.flush();
            fOutputStream.close();

            MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(this, "Save Failed", Toast.LENGTH_SHORT).show();
            return;
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "Save Failed", Toast.LENGTH_SHORT).show();
            return;
        }

How can I save the image in the new directory if not exists and save default if the folder is there in the device?

aman.nepid
  • 2,864
  • 8
  • 40
  • 48

6 Answers6

44

try this it will gives u result sure:

String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/req_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir, fname);
Log.i(TAG, "" + file);
if (file.exists())
    file.delete();
try {
    FileOutputStream out = new FileOutputStream(file);
    bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
    out.flush();
    out.close();
} catch (Exception e) {
    e.printStackTrace();
}

add this one to show in gallery:

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));

look at this link for clear answer: show folder images in gallery

Community
  • 1
  • 1
SubbaReddy PolamReddy
  • 2,083
  • 2
  • 17
  • 23
11

Please use the below code snippet might be help full

String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOutputStream = null;
File file = new File(path + "/Captures/", "screen.jpg");
if (!file.exists()) {
    file.mkdirs();
}

try {
    fOutputStream = new FileOutputStream(file);

    capturedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOutputStream);

    fOutputStream.flush();
    fOutputStream.close();

    MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
} catch (FileNotFoundException e) {
    e.printStackTrace();
    Toast.makeText(this, "Save Failed", Toast.LENGTH_SHORT).show();
    return;
} catch (IOException e) {
    e.printStackTrace();
    Toast.makeText(this, "Save Failed", Toast.LENGTH_SHORT).show();
    return;
}
DragonFire
  • 3,722
  • 2
  • 38
  • 51
Bhavdip Sagar
  • 1,951
  • 15
  • 27
1

Use the following:

File dir = new File(path + "/Captures/");
if(!dir.exists()) {
    dir.mkdirs();
}
File file = new File(path + "/Captures/", "screen.jpg");
 ......
Nermeen
  • 15,883
  • 5
  • 59
  • 72
1

late but might be helpful to someone. use below code it will save the bitmap in external directory more faster because of BufferOutPutStream.

public boolean storeImage(Bitmap imageData, String filename) {
    // get path to external storage (SD card)

    File sdIconStorageDir = null;

    sdIconStorageDir = new File(Environment.getExternalStorageDirectory()
            .getAbsolutePath() + "/myAppDir/");
    // create storage directories, if they don't exist
    if (!sdIconStorageDir.exist()) {
        sdIconStorageDir.mkdirs();
    }
    try {
        String filePath = sdIconStorageDir.toString() + File.separator + filename;
        FileOutputStream fileOutputStream = new FileOutputStream(filePath);
        BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
        //Toast.makeText(m_cont, "Image Saved at----" + filePath, Toast.LENGTH_LONG).show();
        // choose another format if PNG doesn't suit you
        imageData.compress(Bitmap.CompressFormat.PNG, 100, bos);
        bos.flush();
        bos.close();

    } catch (FileNotFoundException e) {
        Log.w("TAG", "Error saving image file: " + e.getMessage());
        return false;
    } catch (IOException e) {
        Log.w("TAG", "Error saving image file: " + e.getMessage());
        return false;
    }
    return true;
}
DragonFire
  • 3,722
  • 2
  • 38
  • 51
Adeeb karim
  • 292
  • 3
  • 9
  • I believe it should be: `!sdIconStorageDir.exists()` and not `exist()` singular (without the 's'). – Devon Mar 13 '21 at 17:47
0

You should take a look in the documentation of File, you'll find the method mkdir(). It is pretty much the same as the unix one : https://developer.android.com/reference/java/io/File.html#mkdir()

ben
  • 1,151
  • 10
  • 20
0

This is how I did in my case in Koltin:

fun getImageUriFromBitmap(context: Context, bitmap: Bitmap?): Uri {
        var filePath = ""
        try {
            filePath = createAndGetFilePath(context)
            val fileOutputStream = FileOutputStream(filePath)
            val bos = BufferedOutputStream(fileOutputStream)
            bitmap?.compress(Bitmap.CompressFormat.PNG, 100, bos)
            bos.flush()
            bos.close()
        } catch (e: FileNotFoundException) {
            Log.w("TAG", "Error saving image file: " + e.message)
        } catch (e: IOException) {
            Log.w("TAG", "Error saving image file: " + e.message)
        }
        return Uri.parse(filePath)
    }

    private fun createAndGetFilePath(context: Context): String {
        val file = File(
            context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), // you can change the path here
            BuildConfig.localImagesFolder // add it in build.gradle under android
        )
        try {
            if (!file.exists()) {
                file.mkdirs()
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
        return file.absolutePath + "/" + System.currentTimeMillis() + ".jpg"
    }
Shailendra Madda
  • 20,649
  • 15
  • 100
  • 138