If you want to save it to internal storage and it will not be displayed in gallery
public static void SaveBitmapToInternalStorage(this Context context, Bitmap bitmap, string filename, string directory)
{
//can change directory as per need
if (directory != null || directory != "") directory = "/" + directory;
var imagesDir = context.GetExternalFilesDir(Android.OS.Environment.DirectoryPictures+ directory);
if (!imagesDir.Exists()) imagesDir.Mkdirs();
var jFile = new Java.IO.File(imagesDir, filename);
var filePath = jFile.AbsoluteFile.ToString();
System.IO.FileStream output = null;
using (output = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
{
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 90, output);
}
output.Close();
}
And to retrieve the saved image
Note: filename and directory should be same in order to retrieve same file
public static Drawable GetDrawableFromInternalStorage(this Context context, string fileName, string directory)
{
//return drawable for imagename from internal storage
if (directory != null || directory != "") directory = "/" + directory;
var imagesDir = context.GetExternalFilesDir(Android.OS.Environment.DirectoryPictures + directory);
if (!imagesDir.Exists()) return null;
var jFile = new Java.IO.File(imagesDir, fileName);
if (jFile.Exists())
{
var img = Drawable.CreateFromPath(jFile.ToString());
return img;
}
return null;
}
And to save image to gallery
public static bool SaveImageToGallery(this Context context, Bitmap bmp, string directory)
{
// First save the picture
string storePath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + File.Separator + directory;
File imgDir = new File(storePath);
if (!imgDir.Exists()) imgDir.Mkdir();
string fileName = System.DateTime.Today.ToLongDateString() + ".jpg";
File file = new File(imgDir, fileName);
try
{
var uri = Android.Net.Uri.FromFile(file);
var os = context.ContentResolver.OpenOutputStream(uri);
//Compress and save pictures by io stream
bool isSuccess = bmp.Compress(Bitmap.CompressFormat.Jpeg, 60, os);
os.Flush();
os.Close();
//Update the database by sending broadcast notifications after saving pictures
context.SendBroadcast(new Intent(Intent.ActionMediaScannerScanFile, uri));
return isSuccess;
}
catch (IOException e) { }
return false;
}
If you want to create unique file name to save to gallery then
File file = File.CreateTempFile(
"Img_", /* prefix */
".jpg", /* suffix */
imgDir /* directory */);