将inkCanvas中的图像保存为png或jpeg文件

Гру*_* БИ 3 c# wpf png save inkcanvas

Here is my wpf code <InkCanvas x:Name="inkCanvas" Margin="9,325,210,193" Background="Azure"></InkCanvas> And also there is a button When pressing the button, i want to save image drawn to a file. here is my code

  private void button1_Click(object sender, RoutedEventArgs e)
    {
        int margin = (int)inkCanvas.Margin.Left;
        int width = (int)inkCanvas.ActualWidth - margin;
        int height = (int)inkCanvas.ActualHeight - margin;
        RenderTargetBitmap rtb = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Default);
        rtb.Render(inkCanvas);


        using (FileStream fs = new FileStream("path", FileMode.Create))
        {
            BitmapEncoder encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(rtb));
            encoder.Save(fs);
        }
    }
Run Code Online (Sandbox Code Playgroud)

But image dusplayed is all black (whatching from an explorer) or complitely white, if opened in paint. What do i do to get an image exactely as drawn? ty.

Mik*_*keT 5

The problem is that you are trying to save Vector Graphics as a Bitmap and thats not possible, so first what you need to do is draw the Vectors and then you can save the Drawing

this class will draw Ink on to a existing bitmap

public class InkImage
{
    public static BitmapFrame MergeInk(StrokeCollection ink, BitmapSource background)
    {
        DrawingVisual drawingVisual = new DrawingVisual();
        using (DrawingContext drawingContext = drawingVisual.RenderOpen())
        {
            drawingContext.DrawImage(background, new Rect(0, 0, background.Width, background.Height));

            foreach (var item in ink)
            {
                item.Draw(drawingContext);
            }
            drawingContext.Close();
            var bitmap = new RenderTargetBitmap((int)background.Width, (int)background.Height, background.DpiX, background.DpiY, PixelFormats.Pbgra32);
            bitmap.Render(drawingVisual);
            return BitmapFrame.Create(bitmap);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

you can then save the bitmap using the JPEG or PNG encoder

  • 我建议使用 StrokeCollection 的 Draw 方法代替迭代所有笔画并单独绘制它们:ink.Draw(drawingContext); 这样也可以正确绘制荧光笔笔划。 (8认同)