简体   繁体   English

如何通过WPF中的SaveFileDialog保存BitmapImage?

[英]How to save BitmapImage via SaveFileDialog from WPF?

The way I try implement it via standart Windows.Forms (to get valide DialogResult.OK) 我尝试通过标准Windows.Forms实现它的方式(以获得有效的DialogResult.OK)

            System.Windows.Forms.SaveFileDialog dlg = new System.Windows.Forms.SaveFileDialog();
            dlg.FileName = "Document"; // Default file name
           // dlg.DefaultExt = ".jpg"; // Default file extension
            dlg.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
            if(dlg.ShowDialog()== System.Windows.Forms.DialogResult.OK) 
if (dlg.DialogResult.HasValue && splashDialog.DialogResult.Value)
            {
              string fName = dlg.FileName; 
              if (dlg.FileName != "")
              {
                 System.IO.Stream fileStream = (System.IO.FileStream)dlg.OpenFile(); 

                  fileStream.Close();
               }
             }

This is using Windows forms but it saves blank image(( 这是使用Windows窗体,但它会保存空白图像((

You can do something like that: 您可以执行以下操作:

var encoder = new JpegBitmapEncoder(); // Or PngBitmapEncoder, or whichever encoder you want
encoder.Frames.Add(BitmapFrame.Create(yourImage));
using (var stream = dlg.OpenFile())
{
    encoder.Save(stream);
}

BTW, there is a SaveFileDialog in WPF too, you don't have to use the one from Windows Forms 顺便说一句,WPF中也有一个SaveFileDialog ,您不必使用Windows窗体中的一个

For WPF code will be like : 对于WPF代码将如下所示:

Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document";             
dlg.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
if (dlg.ShowDialog() == true)
{
    var encoder = new JpegBitmapEncoder(); // Or PngBitmapEncoder, or whichever encoder you want
    encoder.Frames.Add(BitmapFrame.Create(bi));
    using (var stream = dlg.OpenFile())
    {
         encoder.Save(stream);
    }
}

Here bi is the BitmapImage 这里bi是BitmapImage

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM