Search code examples
androidimageandroid-galleryandroid-file

Dynamically created image file cannot be found in Gallery or image picker in Android


I am developing an Android app. In my app, I am creating image file from bitmap then save it to device. The process of creating image file from bitmap and save image to device is okay. The problem is I cannot find that created image in gallery. But the file really exist when I search it from file manager.

Here is my code:

File file = null;
try{
    String fileName = String.valueOf(System.currentTimeMillis())+".jpeg";
    file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), fileName);

    if(file.exists()){
        file.delete();
    }

    OutputStream os = new BufferedOutputStream(new FileOutputStream(file));
    template.getBitmap().compress(Bitmap.CompressFormat.JPEG, 100, os);
    os.close();
    Toast.makeText(context,"Templated saved to your device",Toast.LENGTH_SHORT).show();
}
catch (Exception e)  {
    Toast.makeText(context,e.getMessage(),Toast.LENGTH_SHORT).show();
}

As you can see, I save it in the picture folder. I tried save it in download folder as well. File saved to device successfully but the problem is image is not displayed in Gallery. But exist in file manager. How can I make that image searchable in gallery?


Solution

  • try this:

     File file = null;
            try{
                String fileName = String.valueOf(System.currentTimeMillis())+".jpeg";
                file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), fileName);
    
                if(file.exists())
                {
                    file.delete();
                }
                OutputStream os = new BufferedOutputStream(new FileOutputStream(file));
                template.getBitmap().compress(Bitmap.CompressFormat.JPEG, 100, os);
                os.close();
    
                Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri contentUri = Uri.fromFile(file);
                mediaScanIntent.setData(contentUri);
                sendBroadcast(mediaScanIntent);
                Toast.makeText(context,"Templated saved to your device",Toast.LENGTH_SHORT).show();
            }
            catch (Exception e)
            {
                Toast.makeText(context,e.getMessage(),Toast.LENGTH_SHORT).show();
            }