将位图保存到文件 – Xamarin,Monodroid
我正在尝试将位图图像保存到手机内的目录(图库)中。 该应用程序正在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"); }
这里有一个简单的方法,只使用C#
stuff将Bitmap
作为PNG
文件导出到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(); }
更改:
String filePath = storageDirectory.ToString() + "APPNAME.png";
至:
String filePath = Path.Combine(storageDirectory.ToString(), "APPNAME.png");
原始代码将文件名附加到路径名中的最后一个文件夹,而不添加路径分隔符。 例如, \data\data\sdcard01
路径将创建\data\data\sdcard01
的文件路径。 使用Path.Combine()
可确保在追加目录时使用路径分隔符。