首页 > 解决方案 > 在 Android 中将位图保存到图库

问题描述

我认为这应该很简单,但我无法弄清楚。我不断收到错误:System.IO.DirectoryNotFoundException: Could not find a part of the path "/storage/emulated/0/Pictures/Screenshots/name.jpg".

编码:

string root = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).Path;
File myDir = new File(root + "/Screenshots");
myDir.Mkdirs();

string timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").Format(new Date());
string fname = CommunicationHandler.GetNickname() + "|" + timeStamp + ".jpg";

File file = new File(myDir, fname);
if (file.Exists())
    file.Delete();
try
{
    using (System.IO.Stream outStream = System.IO.File.Create(file.Path))
        {
            finalBitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, outStream);
            outStream.Flush();
            outStream.Close();
        }
}
catch (Exception e)
{
    Toast.MakeText(Activity, e.ToString(), ToastLength.Long).Show();
}

另外,我无法手动访问 /storage/emulated/0..

为什么我无法将位图保存到我的手机图库中?上面的代码有什么问题?

标签: c#xamarinbitmapstreamandroid-external-storage

解决方案


如果你想创建一个新目录,你可以使用 System.IO.Directory.CreateDirectory(root);它来创建它。

//create a directory called MyCamera
    string root = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDcim).ToString() + "/MyCamera/";

   //create the Directory
    System.IO.Directory.CreateDirectory(root);

推荐阅读