Save Bitmap in Android as JPEG in External Storage in a folder

aman.nepid picture aman.nepid · Dec 27, 2012 · Viewed 56.4k times · Source

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?

Answer

SubbaReddy PolamReddy picture SubbaReddy PolamReddy · Dec 27, 2012

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