Android - Save images in an specific folder

Goblinch picture Goblinch · Aug 2, 2013 · Viewed 97.3k times · Source

I need to save the pictures taken with my app in an specific folder. I've read many solutions to this problem but I couldn't make any of them work so I ask for help.

MainActivity.java

public void onClick(View v) {

    Intent camera = new Intent(
            android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

    //Folder is already created
    String dirName = Environment.getExternalStorageDirectory().getPath()
            + "/MyAppFolder/MyApp" + n + ".png";

    Uri uriSavedImage = Uri.fromFile(new File(dirName));
    camera.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
    startActivityForResult(camera, 1);

    n++;
}

AndroidManifest.xml

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Answer

mdDroid picture mdDroid · Aug 2, 2013

Go through the following code , its working fine for me.

private void createDirectoryAndSaveFile(Bitmap imageToSave, String fileName) {

    File direct = new File(Environment.getExternalStorageDirectory() + "/DirName");

    if (!direct.exists()) {
        File wallpaperDirectory = new File("/sdcard/DirName/");
        wallpaperDirectory.mkdirs();
    }

    File file = new File("/sdcard/DirName/", fileName);
    if (file.exists()) {
        file.delete();
    }
    try {
        FileOutputStream out = new FileOutputStream(file);
        imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}