【问题标题】:How can I save an image from ink canvas?如何从墨水画布中保存图像?
【发布时间】:2013-07-30 03:32:42
【问题描述】:

我正在尝试从墨水画布中保存图像,但是保存后它不会创建任何文件,这是我的代码:

RenderTargetBitmap rtb = new RenderTargetBitmap(
    (int)canvas.Width, (int)canvas.Height, 0, 0, PixelFormats.Default);

rtb.Render(this.canvas);

JpegBitmapEncoder encoder = new JpegBitmapEncoder();

encoder.Frames.Add(BitmapFrame.Create(rtb));

using(var file = new FileStream(@"C:\test.jpg", FileMode.Create))
{
   encoder.Save(file);
}

但是,即使我更改目录,它也不会创建任何文件。没有调用异常,也没有显示错误。代码运行正常,没有任何问题,但要生成的文件不存在。

【问题讨论】:

  • 我已经更新了标题(随时恢复/改进)和removed "thank you notes"。请改为添加有关您看到的异常(如果有)的信息,并使用确切的错误消息更新您的帖子。

标签: c# filestream inkcanvas jpegbitmapencoder


【解决方案1】:

尝试使用保存文件对话框

这是我在 vb.net 中的“添加签名”类中使用的示例代码

点击按钮会出现一个保存文件对话框,输入文件名并按保存后,它将保存为png图像(我使用pngBitmap编码器)

这与您使用的格式相同,但添加了一个保存文件对话框。

顺便说一句。 WPFControl.Inkcanvas1 是我的inkcanvas

'buttonSaveAsClick


   'open save file dialog box
    Dim sfd As New SaveFileDialog()
    sfd.Filter = "Png Files(*.png)|*.png"

    'save file as png (render bitmap and convert/save to png)
    Dim result As Nullable(Of Boolean) = sfd.ShowDialog()
    Dim fileName As String = ""

    If result = True Then
        fileName = sfd.FileName

        Dim size As Size = New Point(750, 400) '= WPFControl.InkCanvas1.RenderSize 
        Console.WriteLine(WPFControl.InkCanvas1.RenderSize)
        Dim rtb As New RenderTargetBitmap(CInt(size.Width), CInt(size.Height), 96, 96, Windows.Media.PixelFormats.Pbgra32)
        rtb.Render(WPFControl.InkCanvas1)
        Dim png As New PngBitmapEncoder()
        png.Frames.Add(BitmapFrame.Create(rtb))
        If String.IsNullOrEmpty(fileName) = True Then
            MsgBox("Please Enter a File Name", MsgBoxStyle.Exclamation, "File Name required!")
            Exit Sub

        Else
            Console.WriteLine(sfd.FileName)
            Console.WriteLine(convertImage.ConvertImageFiletoBytes(sfd.FileName))
        End If


        Using stm As Stream = File.Create(fileName)
            png.Save(stm)

        End Using
    End If

【讨论】:

    【解决方案2】:

    好的,这是我做到的一种方式,这种方式在调试文件夹中导出“test.png”。方法很简单,首先创建一个 InkCanvas,我将其命名为 ink 以用于本示例。还要创建一个具有 on click 事件处理程序的按钮。在单击事件处理程序上的那个按钮中粘贴这个。

    InkCanvasWindow.xaml.cs

    Rect bounds = VisualTreeHelper.GetDescendantBounds(ink);
                double dpi = 96d;
    
                RenderTargetBitmap rtb = new RenderTargetBitmap((int)bounds.Width, (int)bounds.Height, dpi, dpi, System.Windows.Media.PixelFormats.Default);
                DrawingVisual dv = new DrawingVisual();
                using (DrawingContext dc = dv.RenderOpen())
                {
                    VisualBrush vb = new VisualBrush(ink);
                    dc.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size));
                }
                rtb.Render(dv);
    
                BitmapEncoder pngEncoder = new PngBi tmapEncoder();
                pngEncoder.Frames.Add(BitmapFrame.Create(rtb));
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    pngEncoder.Save(ms);
                    System.IO.File.WriteAllBytes("test.png", ms.ToArray());
    
    • 记住“ink”是 InkCanvas 的名称。

    【讨论】:

      【解决方案3】:

      XAML

          <Window x:Class="WpfInkCavasSaveImage.MainWindow"
                  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                  Title="MainWindow"  Height="1091" Width="873" WindowState="Maximized">
              <Grid Margin="0,0,0,173" >
                  <Grid.RowDefinitions>
                      <RowDefinition Height="1200*" />
                      <RowDefinition Height="50" />
                  </Grid.RowDefinitions>    
                  <InkCanvas HorizontalAlignment="Stretch" Margin="1,1,1,10" x:Name="inkCanvas1" VerticalAlignment="Stretch" Width="Auto" RenderTransformOrigin="0.5,0.5" Background="LightGreen" SnapsToDevicePixels="True" IsManipulationEnabled ="True"  Grid.RowSpan="2">
                      <InkCanvas.CacheMode>
                          <BitmapCache/>
                      </InkCanvas.CacheMode>
                      <InkCanvas.DefaultDrawingAttributes>
                          <DrawingAttributes Color="Black" FitToCurve="True" Height="2.0031496062992127" IgnorePressure="False" IsHighlighter="False" StylusTip="Ellipse" StylusTipTransform="Identity" Width="2.0031496062992127"/>    
                      </InkCanvas.DefaultDrawingAttributes>
                  </InkCanvas>
                  <Button x:Name="btnSaveImage" Content="Save Ink Canvas" Height="41" Width="155" Canvas.Left="100" Canvas.Top="900"  VerticalAlignment="Top" HorizontalAlignment="Left" RenderTransformOrigin="1.417,14.6" Margin="15,93,0,-84" Background="SkyBlue" Click="btnSaveInkCanvas" Grid.Row="1" BorderBrush="{x:Null}"/>
              </Grid>
              
          </Window>
      

      C#

          using Microsoft.Win32;
          using System;
          using System.Collections.Generic;
          using System.IO;
          using System.Linq;
          using System.Security.AccessControl;
          using System.Text;
          using System.Threading.Tasks;
          using System.Windows;
          using System.Windows.Controls;
          using System.Windows.Data;
          using System.Windows.Documents;
          using System.Windows.Input;
          using System.Windows.Media;
          using System.Windows.Media.Imaging;
          using System.Windows.Navigation;
          using System.Windows.Shapes;
          
          namespace WpfInkCavasSaveImage
          {
              /// <summary>
              /// Interaction logic for MainWindow.xaml
              /// </summary>
              public partial class MainWindow : Window
              {
                  public MainWindow()
                  {
                      InitializeComponent();
                      inkCanvas1.Width = System.Windows.SystemParameters.WorkArea.Width;
                      inkCanvas1.Height = System.Windows.SystemParameters.WorkArea.Height;
                  }
                  private void btnSaveInkCanvas(object sender, RoutedEventArgs e)
                  {
                      string subpath = Directory.GetCurrentDirectory();
                      SaveFileDialog saveFileDialog12 = new SaveFileDialog();
                      saveFileDialog12.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif|Png File|*.png";
                      saveFileDialog12.Title = "Save an Image File";
                      saveFileDialog12.InitialDirectory = subpath;
                      saveFileDialog12.ShowDialog();
          
                      if (saveFileDialog12.FileName == "") return;
                      subpath = saveFileDialog12.FileName.Substring(0, saveFileDialog12.FileName.Length - saveFileDialog12.SafeFileName.Length);
                 
                      RenderTargetBitmap rtb = new RenderTargetBitmap((int)inkCanvas1.Width, (int)inkCanvas1.Height, 96d, 96d, PixelFormats.Default);
                      rtb.Render(inkCanvas1);
                      DrawingVisual dvInk = new DrawingVisual();
                      DrawingContext dcInk = dvInk.RenderOpen();
                      dcInk.DrawRectangle(inkCanvas1.Background, null, new Rect(0d, 0d, inkCanvas1.Width, inkCanvas1.Height));
                      foreach (System.Windows.Ink.Stroke stroke in inkCanvas1.Strokes)
                      {
                          stroke.Draw(dcInk);
                      }
                      dcInk.Close();
          
                      FileStream fs = File.Open(saveFileDialog12.FileName, FileMode.OpenOrCreate);//save bitmap to file
                      System.Windows.Media.Imaging.JpegBitmapEncoder encoder1 = new JpegBitmapEncoder();
                      encoder1.Frames.Add(BitmapFrame.Create(rtb));
                      encoder1.Save(fs);
                      fs.Close();
                  }
              }
          }
      

      【讨论】:

      • 请解释您的代码在做什么以及它如何解决问题
      • 请检查并测试代码一切正常。也没有太多解释代码了。
      猜你喜欢
      • 1970-01-01
      • 2013-03-11
      • 2021-03-07
      • 2014-01-27
      • 1970-01-01
      • 2018-04-09
      • 1970-01-01
      • 1970-01-01
      • 2014-02-16
      相关资源
      最近更新 更多