2

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

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);
}

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

4

3 回答 3

2

尝试使用保存文件对话框

这是我在 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
于 2015-10-19T08:00:02.650 回答
0

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();
            }
        }
    }
于 2018-07-06T10:05:49.827 回答
0

好的,这是我做到的一种方式,这种方式在调试文件夹中导出“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());
  • 记住“墨水”是 InkCanvas 的名称。
于 2021-09-02T11:47:36.920 回答