1

I use the following code to create a folder in my phone memory and save a bitmap into that folder. The code works fine and the bitmap is getting stored as JPEG. But the problem is I cannot see that image in the Gallery app like images from other apps like Whatsapp,Instagram etc. I have to go to the File Manager app to see it. Why it is not showing in Gallery? Here is my code:

saveButton.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v)
       {
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String imageFileName = "JPEG_" + timeStamp + ".jpg";
            CreateDirectoryAndSaveFile(mainImageBitmap, imageFileName);
       }
});

private void CreateDirectoryAndSaveFile(Bitmap imageToSave, String fileName)
    {
        File direct = new File(Environment.getExternalStorageDirectory() + "/" + getString(R.string.app_name));

        if (!direct.exists()) {
            File wallpaperDirectory = new File("/sdcard/" + getString(R.string.app_name) + "/");
            wallpaperDirectory.mkdirs();
        }

        File file = new File(new File("/sdcard/" + getString(R.string.app_name) + "/"), fileName);
        if (file.exists()) {
            file.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(file);
            imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            Toast.makeText(getActivity(), "Image saved to Gallery successfully", Toast.LENGTH_SHORT).show();
        } catch (Exception e)
        {
            Toast.makeText(getActivity(), "Error", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
Jayesh Babu
  • 1,389
  • 2
  • 20
  • 34
  • the gallery displays images stored on the [media store provider](https://developer.android.com/reference/android/provider/MediaStore) – Mittal Varsani Nov 29 '18 at 05:29

1 Answers1

1

After you save the image in a file, you will need to tell the media store to scan for the file.

For this use:

MediaScannerConnection.scanFile(String path, String mimeType)

or

MediaScannerConnection.scanFile(Context context, String[] paths, String[] mimeTypes,
        OnScanCompletedListener callback) 

Mime type for JPEG image is "image/jpeg".

Nabin Bhandari
  • 15,949
  • 6
  • 45
  • 59