Saving a bitmap to a file - Xamarin, Monodroid

I am trying to save a bitmap in a directory (gallery) inside my phone. The application is being developed in Xamarin, therefore C # code.

I cannot figure out how to create a directory and save a bitmap. Any suggestions?

public void createBitmap(View view){ 
    view.DrawingCacheEnabled = true; 
    view.BuildDrawingCache (true); 
    Bitmap m_Bitmap = view.GetDrawingCache(true);

    String storagePath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
    Java.IO.File storageDirectory = new Java.IO.File(storagePath);
    //storageDirectory.mkdirs ();


    //save the bitmap
    //MemoryStream stream = new MemoryStream ();
    //m_Bitmap.Compress (Bitmap.CompressFormat.Png, 100, stream);
    //stream.Close();


    try{

        String filePath = storageDirectory.ToString() + "APPNAME.png";
        FileOutputStream fos = new FileOutputStream (filePath);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        m_Bitmap.Compress (Bitmap.CompressFormat.Png, 100, bos);
        bos.Flush();
        bos.Close();
    } catch (Java.IO.FileNotFoundException e) {
        System.Console.WriteLine ("FILENOTFOUND");
    } catch (Java.IO.IOException e) {
        System.Console.WriteLine ("IOEXCEPTION");
    }
+4
source share
2 answers

This is a slim way to export Bitmapas a PNGfile to an SD card using only C#stuff:

void ExportBitmapAsPNG(Bitmap bitmap)
{
    var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
    var filePath = System.IO.Path.Combine(sdCardPath, "test.png");
    var stream = new FileStream(filePath, FileMode.Create);
    bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);
    stream.Close();
}
+16
source

Edit:

String filePath = storageDirectory.ToString() + "APPNAME.png";

To:

String filePath = Path.Combine(storageDirectory.ToString(), "APPNAME.png");

. , \data\data\sdcard01 \data\data\sdcard01APPNAME.png. Path.Combine() , .

+3

All Articles