【问题标题】:Saving Bitmap to File - Xamarin, Monodroid将位图保存到文件 - Xamarin、Monodroid
【发布时间】:2014-09-22 14:01:55
【问题描述】:

我正在尝试将位图图像保存到手机内的目录(图库)中。该应用程序是在 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# android bitmap xamarin xamarin.android


    【解决方案1】:

    这是一种slim方法,仅使用C# 东西将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();
    }
    

    【讨论】:

    • 如何在不压缩的情况下写出原始bmp数据?
    • @gonzobrains 我不知道这是否或如何可能。对不起。
    • 您应该使用“.Dispose()”从内存中释放蒸汽和位图,或者使用“using(){}”可能会更好。
    • 当我压缩它时,我失去了图像的质量。有没有办法在不传递给这个压缩函数的情况下保存它?此外,@testing 帖子仅显示通过将其传递给 compress 函数来转换为字节数组。
    • @Fabiotk:你试过CopyPixelsToBuffer()吗? Here 是关于此的帖子。
    【解决方案2】:

    变化:

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

    收件人:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-11
      • 1970-01-01
      • 2012-08-13
      • 2013-03-16
      • 2011-05-08
      • 1970-01-01
      • 1970-01-01
      • 2012-07-01
      相关资源
      最近更新 更多