Search code examples
c#wpfimageinkcanvas

Render an Image from a StrokeCollection in c#


I need to get an Image from a StrokeCollection, but have no access to the Visual (InkCanvas) itself because of the mvvm structure. Is there possibly an easy way to get this done?

XAML:

<InkCanvas x:Name="paintSurface" Grid.Row="0" Opacity="0.2" Strokes="{Binding Strokes}">
    <InkCanvas.DefaultDrawingAttributes>
        <DrawingAttributes Color="Black" Width="10" Height="10"/>
    </InkCanvas.DefaultDrawingAttributes>
</InkCanvas>

Viewmodel:

private StrokeCollection _strokes;
public StrokeCollection Strokes {
    get => _strokes;
    set => SetProperty(ref _strokes, value);
} 

Now i just want to convert the StrokeCollection into some form of processable Image, wether it is a Bitmap, BitmapImage, Mat, EmguCV Image, is not important. Thx in advance :)


Solution

  • I solved my Problem by handing the StrokeCollection to a helper class where i just create a new InkCanvas, add the Strokes (from the Original InkCanvas in the UI) and render it.

    public static Bitmap convertStrokestoImage(StrokeCollection strokes, int width, int height)
        {
            InkCanvas InkyStinky = new InkCanvas();
            InkyStinky.RenderSize = new System.Windows.Size(width, height);
            InkyStinky.Strokes.Add(strokes);
            RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
            bmp.Render(InkyStinky);
            MemoryStream stream = new MemoryStream();
            BitmapEncoder encoder = new BmpBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bmp));
            encoder.Save(stream);
            Bitmap b = new Bitmap(stream);
            return b;
        }