How to save a WPF chart toolkit as image in the clipboard?

194 views Asked by At

I already was using Windows form chart and I was able to save the chart control in the clipboard with these codes:

    Dim stream As New System.IO.MemoryStream()
    SummaryChart.SaveImage(stream, System.Drawing.Imaging.ImageFormat.Bmp)
    Dim bmp As New System.Drawing.Bitmap(stream)
    Clipboard.SetDataObject(bmp)

But since the requirements have changed then I had to create the chart in the view with the use of WPF Chart toolkit :

xmlns:dv="clr-namespace:System.Windows.Controls.DataVisualization;assembly=System.Windows.Controls.DataVisualization.Toolkit"

SummaryChart.SaveImage does not work anymore. What is the best way of doing what I was doing before?

I have read this article: Get a bitmap image from a Control view and tried these codes:

 Dim rtb = New RenderTargetBitmap(CInt(SummariesChart.ActualWidth), 
 CInt(SummariesChart.ActualHeight), 96, 96, PixelFormats.Pbgra32)
 rtb.Render(SummariesChart)
 Dim png  = New PngBitmapEncoder()
 png.Frames.Add(BitmapFrame.Create(rtb))
 Dim stream  = New MemoryStream()
 png.Save(stream)
 Clipboard.SetImage(rtb)

But still, it doesn't work. Can anybody help me?

Thanks.

1

There are 1 answers

2
Muthukumar K On

To save WPF Chart toolkit image as like below code. Add the BitMapFrame in Encoder.Frames and then save the image.

Public Shared Sub SaveAsImage(ByVal element As FrameworkElement, ByVal filepath As String, ByVal width As Integer, ByVal height As Integer)
element.Width = width
element.Height = height
element.Measure(New Size(width, height))
element.Arrange(New Rect(0, 0, width, height))
element.UpdateLayout()
Dim target = New RenderTargetBitmap(width, height, 96, 96, System.Windows.Media.PixelFormats.Pbgra32)
target.Render(element)
Dim encoder = New PngBitmapEncoder()
Dim outputFrame = BitmapFrame.Create(target)
encoder.Frames.Add(outputFrame)

Using file = File.OpenWrite(filepath)
    encoder.Save(file)
End Using End Sub