实现函数:
/// <summary> /// 保存图片到文件 /// </summary> /// <param name="image">图片数据</param> /// <param name="filePath">保存路径</param> private void SaveImageToFile(BitmapSource image, string filePath) { BitmapEncoder encoder = GetBitmapEncoder(filePath); encoder.Frames.Add(BitmapFrame.Create(image)); using (var stream = new FileStream(filePath, FileMode.Create)) { encoder.Save(stream); } } /// <summary> /// 根据文件扩展名获取图片编码器 /// </summary> /// <param name="filePath">文件路径</param> /// <returns>图片编码器</returns> private BitmapEncoder GetBitmapEncoder(string filePath) { var extName = Path.GetExtension(filePath).ToLower(); if (extName.Equals(".png")) { return new PngBitmapEncoder(); } else { return new JpegBitmapEncoder(); } }
最终调用的方法:
/// <summary> /// 保存图片菜单点击事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void menuSaveImage_Click(object sender, RoutedEventArgs e) { try { if (imageData == null) { return; } var dlg = new Microsoft.Win32.SaveFileDialog(); dlg.Filter = "PNG图片(*.png)|*.png|JPEG图片(*.jpg)|*.jpg|所有文件(*.*)|*.*"; var rst = dlg.ShowDialog(); if (rst == true) { var fileName = dlg.FileName; SaveImageToFile(imageData, fileName); MessageBox.Show("保存成功"); } } catch (Exception ex) { logger.Error(ex); MessageBox.Show(ex.Message); } }