将位图保存到文件 - Xamarin,Monodroid

时间:2014-09-22 14:01:55

标签: c# android bitmap xamarin xamarin.android

我正在尝试将位图图像保存到手机内的目录(图库)中。该应用程序正在Xamarin中开发,因此代码为C#。

我似乎无法弄清楚如何制作目录,并保存位图。有什么建议吗?

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");
    }

2 个答案:

答案 0 :(得分:19)

这是一种苗条方式,只使用Bitmap内容将PNG C#文件导出到SD卡:

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();
}

答案 1 :(得分:3)

变化:

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

要:

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

您的原始代码会将文件名附加到路径名中的最后一个文件夹,而不添加路径分隔符。例如,\data\data\sdcard01的路径将创建\data\data\sdcard01APPNAME.png的文件路径。使用Path.Combine()可确保在追加目录时使用路径分隔符。