Coo*_*ova 7 c# android bitmap xamarin.android xamarin
我正在尝试将位图图像保存到手机内的目录(图库)中.该应用程序正在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");
}
Run Code Online (Sandbox Code Playgroud)
kao*_*ick 21
这这里是一个苗条的出口方式Bitmap为PNG-file只使用SD卡C#的东西:
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();
}
Run Code Online (Sandbox Code Playgroud)
改变:
String filePath = storageDirectory.ToString() + "APPNAME.png";
Run Code Online (Sandbox Code Playgroud)
到:
String filePath = Path.Combine(storageDirectory.ToString(), "APPNAME.png");
Run Code Online (Sandbox Code Playgroud)
您的原始代码将文件名附加到路径名中的最后一个文件夹,而不添加路径分隔符。例如,路径 of\data\data\sdcard01将创建文件路径\data\data\sdcard01APPNAME.png. 使用Path.Combine()可确保在附加目录时使用路径分隔符。