0

I'm trying to found a way (compatible with android kitkat and next) to write photos on the SD Card and make them visible to the gallery app.

  • If I use Environment.getExternalStoragePublicDirectory , samsung devices return a path in internal memory (/storage/emulated/0/ ... )
  • If I use Context.getExternalFilesDirs , there are two results : the first one on internal storage, and the second one on SD Card. Ok, I can write inside and the photo is on the SDCard. But I can't see it in the Galery app :'(

I have tried to write directly on /storage/externalSdCard/DCIM/ but of course I can't since I'm running kitkat.

Cœur
  • 37,241
  • 25
  • 195
  • 267
gRRosminet
  • 137
  • 1
  • 8
  • possible duplicate of [android - save image into gallery](http://stackoverflow.com/questions/8560501/android-save-image-into-gallery) – runDOSrun Feb 13 '15 at 11:30
  • http://developer.android.com/reference/android/os/Environment.html#DIRECTORY_PICTURES – A.S. Feb 13 '15 at 11:31

2 Answers2

0
void saveImage() {
        File filename;
        try {
            String path = Environment.getExternalStorageDirectory().toString();

            new File(path + "/folder/subfolder").mkdirs();
            filename = new File(path + "/folder/subfolder/image.jpg");

            FileOutputStream out = new FileOutputStream(filename);

            bitMapImg.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();

            MediaStore.Images.Media.insertImage(getContentResolver(), filename.getAbsolutePath(), filename.getName(), filename.getName());

            Toast.makeText(getApplicationContext(), "File is Saved in  " + filename, 1000).show();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
Md Hussain
  • 411
  • 4
  • 10
  • Thanks. MediaStore.Images.Media.insertImage() worked. But then I deleted file from the galery and re-run my test code. And now it does'nt work anymore : I get a file not found exception whereas the file is present (I've checked this point 3 times) – gRRosminet Feb 13 '15 at 12:27
  • surround this code with try catch(Filenotfoundexeption e) String path make it global variable and on oncreate activity path = Environment.getExternalStorageDirectory().toString(); new File(path + "/folder/subfolder").mkdirs(); – Md Hussain Feb 13 '15 at 12:44
0

Ok, I can write inside and the photo is on the SDCard. But I can't see it in the Galery app

First, when you are done writing to the file, call flush(), then getFD().sync(), then close(), all on your FileOutputStream.

Then, use MediaScannerConnection and its scanFile() method to get the newly-written file indexed by the MediaStore.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Thanks, this is the final solution MediaScannerConnection.scanFile(this, new String [] {fDst.getAbsolutePath()} , null, null); – gRRosminet Feb 13 '15 at 13:03