0

Given a bitmap that I want to save to a special folder in the public Gallery on the phone, I tried this:

public static void saveToGallery(Context context, Bitmap bitmap) {
    File path = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), File.separator + "FolderForMyApp");
    path.mkdirs();
    File imageFile = new File(path, "image_name.png");
    FileOutputStream out = null;
    try {
        out = new FileOutputStream(imageFile);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
        out.flush();
        out.close();
    }
    catch (IOException e) {
        Log.w(TAG, "Could not resolve file stream: " + e);
    }
}

However it does not actually show up in the Gallery. What am I doing wrong?

KaliMa
  • 1,970
  • 6
  • 26
  • 51
  • 1
    https://stackoverflow.com/questions/32789157/how-to-write-files-to-external-public-storage-in-android-so-that-they-are-visibl – CommonsWare Nov 30 '16 at 20:36
  • @CommonsWare So is it correct to add the line `MediaScannerConnection.scanFile(context, new String[]{imageFile.getAbsolutePath()}, new String[]{"image/png"}, null);`? – KaliMa Nov 30 '16 at 20:40
  • 1
    That should work. Note that this work is asynchronous, both in terms of updating the `MediaStore`, and then any given gallery-type app necessarily updating its UI based on the `MediaStore` changes. – CommonsWare Nov 30 '16 at 20:43
  • @CommonsWare I presume that's what the third argument is for (callback function when the MediaStore is updated)? – KaliMa Nov 30 '16 at 20:44
  • If you mean the fourth argument, then yes, that should let you know when the `MediaStore` itself is updated. – CommonsWare Nov 30 '16 at 20:45
  • I misspoke, indeed I meant fourth. Thank you! – KaliMa Nov 30 '16 at 20:46
  • 1
    `I want to save to a special folder in the public Gallery on the phone, `. The way you talk about it! You cannot store files to the gallery as the Gallery app is an app and no storage place. You can only save your files to -specific-folders on external and removable storage. And then there happens to be a Media Store who indexes all those media files. And a Gallery app who uses this index to show your pictures. – greenapps Nov 30 '16 at 21:12
  • @greenapps Thanks for the clarification, good to know – KaliMa Nov 30 '16 at 21:17

1 Answers1

0

It does not appear on the gallery because you have to refresh the gallery, so it knows about the new file

   // Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this,
        new String[] { file.toString() }, null,
        new MediaScannerConnection.OnScanCompletedListener() {
    public void onScanCompleted(String path, Uri uri) {
        Log.i("ExternalStorage", "Scanned " + path + ":");
        Log.i("ExternalStorage", "-> uri=" + uri);
    }
});

Sry about the formatting. I'm on my phone.

bogdanN
  • 183
  • 10