To add an image into the android gallery we can use MediaScannerConnection class. The system scans the SD card when it is mounted to find any new image (and other) files.So sometimes we need to restart the phone to get updated. To solve this we can programmatically add a file, using this class.
public void saveImageBitmap(byte[] sourceImageData, Context context) {
Bitmap scaledBitmap = null;
try {
ContentValues image = new ContentValues();
image.put(Media.DISPLAY_NAME, "sample_" + System.currentTimeMillis());
image.put(Media.MIME_TYPE, "image/jpeg");
Uri uri = context.getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, image);
Bitmap bitmap = BitmapFactory.decodeByteArray(sourceImageData, 0, sourceImageData.length);
Bitmap rotateBitmap = null;
Matrix matrix = new Matrix();
rotateBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
OutputStream ops = context.getContentResolver().openOutputStream(uri);
rotateBitmap.compress(Bitmap.CompressFormat.JPEG, 90, ops);
ops.close();
Cursor c = context.getContentResolver().query(uri, null, null, null, null);
c.moveToFirst();
String imagePath = c.getString(1);
c.close();
SingleScanMediaFile mScanner = new SingleScanMediaFile(context, imagePath);
mScanner.onScanCompleted(imagePath, Uri.fromFile(new File(imagePath)));
} catch (Exception e) {
e.printStackTrace();
}
}
public static class SingleScanMediaFile implements MediaScannerConnectionClient {
private MediaScannerConnection mMediaScanner;
private String uri;
SingleScanMediaFile (Context c, String uri) {
this.uri = uri;
mMediaScanner = new MediaScannerConnection(c, this);
mMediaScanner.connect();
}
@Override public void onMediaScannerConnected() {
Log.i("Sample", "MEDIA SCANNER CONNECTED");
try {
mMediaScanner.scanFile(uri, null);
} catch (Exception e) {
e.printStackTrace();
mMediaScanner.disconnect();
}
}
@Override public void onScanCompleted(String path, Uri uri) {
Log.i("sample", "MEDIA SCANING COMPLETED");
mMediaScanner.disconnect();
}
}