update android image gallery with newly created bitmap

两盒软妹~` 提交于 2019-11-29 05:12:29

Use this code to save an image Bitmap in android device gallery

public void savePhoto(Bitmap bmp)
{
imageFileFolder = new File(Environment.getExternalStorageDirectory(),"Rotate");
imageFileFolder.mkdir();
FileOutputStream out = null;
Calendar c = Calendar.getInstance();
String date = fromInt(c.get(Calendar.MONTH))
            + fromInt(c.get(Calendar.DAY_OF_MONTH))
            + fromInt(c.get(Calendar.YEAR))
            + fromInt(c.get(Calendar.HOUR_OF_DAY))
            + fromInt(c.get(Calendar.MINUTE))
            + fromInt(c.get(Calendar.SECOND));
imageFileName = new File(imageFileFolder, date.toString() + ".jpg");
try
{
 out = new FileOutputStream(imageFileName);
 bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
 out.flush();
 out.close();
 scanPhoto(imageFileName.toString());
 out = null;
} catch (Exception e)
{
e.printStackTrace();
}
}


public String fromInt(int val)
{
return String.valueOf(val);
}


public void scanPhoto(final String imageFileName)
{
msConn = new MediaScannerConnection(PreviewDemo1.this,new MediaScannerConnectionClient()
{
public void onMediaScannerConnected()
{
msConn.scanFile(imageFileName, null);
Log.i("msClient obj  in Photo Utility","connection established");
}
public void onScanCompleted(String path, Uri uri)
{
msConn.disconnect();
Log.i("msClient obj in Photo Utility","scan completed");
}
});
msConn.connect();
} 

Here i am saving the image in " Rotate " folder if you dont want that you can change it easily in savePhoto method.

I know i am a little late to answer this but i guess for anyone else reading this the answer given by surendra is right and that using the MediaScannerConnection is a way to update the gallery. As for the way nevva was suggesting the changes to his code are :

    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    getApplicationContext().sendBroadcast(mediaScanIntent);

I have written down a detailed post about scanning media files in Android. http://androidyue.github.io/blog/2014/01/19/scan-media-files-in-android/ I hope this could help you.

Simply use MediaScannerConnection after you saved your bitmap to sd:

MediaScannerConnection.scanFile(this,
                new String[] { Bitmapfile.getAbsolutePath() }, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    public void onScanCompleted(String path, Uri uri) {
                        //now visible in gallery
                    }
                }
            );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!