3

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

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.

  • take a look: http://stackoverflow.com/questions/4067448/converting-image-to-bitmap-turns-background-black i had a similar problem but with winForms – Alex Dec 01 '16 at 14:57
  • @Alex doesn't seem that similar you were trying to save a bitmap with transparency in a encoder that didn't support it, this encoder does support it, but it may be the default pixel format isn't including an Alpha channel, or it could be that the render isn't rendering the background and vectors correctly – MikeT Dec 01 '16 at 15:20

1 Answers1

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

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

MikeT
  • 5,398
  • 3
  • 27
  • 43
  • 8
    Instead of iterating over all the strokes and drawing them individually, I would suggest to use StrokeCollection's Draw method instead: ink.Draw(drawingContext); That way highlighter strokes are drawn correctly as well. – wilford Feb 10 '17 at 09:33