So we have a WPF application that shows some charts created using the Live Charts library. However I got the task to render the charts in the background, and save them to a PNG image without displaying a WPF window. I found an article online that takes a UserControl and does exactly that, but trying it myself I only get a transparent image of 80 by 50 pixels.
Unfortunately I am not very familiar with the WPF internals of rendering, so any help is really appreciated. This is my code rendered down to the bare minimum with the simplest chart example from LiveChart itself.
using System;
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using LiveCharts.Wpf;
using LiveCharts.Geared;
using LiveCharts;
namespace Screenshot2Pdf {
class Program {
[STAThread]
static void Main(string[] args) {
var Series = new SeriesCollection();
var r = new Random();
for (var i = 0; i < 30; i++) // 30 series
{
var trend = 0d;
var values = new double[10000];
for (var j = 0; j < 10000; j++) // 10k points each
{
trend += (r.NextDouble() < .8 ? 1 : -1) * r.Next(0, 10);
values[j] = trend;
}
var series = new LineSeries {
Values = values.AsGearedValues().WithQuality(Quality.Low),
Fill = Brushes.Transparent,
StrokeThickness = .5,
PointGeometry = null //use a null geometry when you have many series
};
Series.Add(series);
}
var chart = new CartesianChart();
chart.Series = Series;
chart.BeginInit();
chart.EndInit();
// Measure and arrange the tile
chart.Measure(new System.Windows.Size {
Height = double.PositiveInfinity,
Width = double.PositiveInfinity
});
chart.Arrange(new System.Windows.Rect(0, 0,
chart.DesiredSize.Width,
chart.DesiredSize.Height));
chart.UpdateLayout();
RenderTargetBitmap rtb = new RenderTargetBitmap((int)chart.DesiredSize.Width, (int)chart.DesiredSize.Height, 96, 96, PixelFormats.Pbgra32);
rtb.Render(chart);
PngBitmapEncoder png = new PngBitmapEncoder();
png.Frames.Add(BitmapFrame.Create(rtb));
MemoryStream stream = new MemoryStream();
png.Save(stream);
var image = System.Drawing.Image.FromStream(stream);
image.Save(#"D:\bitmap.png");
}
}
}
Oké I am not sure why. As said before I am not very familiar with WPF's internal rendering mechanism and what triggers it, but the solution is to wrap the Chart in a Viewbox. The following code does the trick:
var viewbox = new Viewbox();
viewbox.Child = chart;
viewbox.Measure(chart.RenderSize);
viewbox.Arrange(new Rect(new Point(0, 0), chart.RenderSize));
chart.Update(true, true); //force chart redraw
viewbox.UpdateLayout();
// RenderTargetBitmap rtb = new RenderTargetBitmap((int)chart.DesiredSize.Width, (int)chart.DesiredSize.Height, 96, 96, PixelFormats.Pbgra32);
var rtb = new RenderTargetBitmap(500, 500, 96, 96, PixelFormats.Default);
rtb.Render(chart);
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(rtb));
using (var stream = File.OpenWrite(#"D:\bitmap.png")) {
encoder.Save(stream);
}
Related
I'm trying to export a chart as a PNG file (without having to render it in the UI) and have implemented the following code for LiveCharts v0 which works fine...
LiveCharts.Wpf.CartesianChart control = new LiveCharts.Wpf.CartesianChart()
{
// Series = ...
Width = 700,
Height = 700,
DisableAnimations = true
};
var viewbox = new Viewbox();
viewbox.Child = control;
viewbox.Measure(control.RenderSize);
viewbox.Arrange(new Rect(new System.Windows.Point(0, 0), control.RenderSize));
control.Update(true, true); //force chart redraw
viewbox.UpdateLayout();
var encoder = new PngBitmapEncoder();
var bitmap = new RenderTargetBitmap((int)control.ActualWidth, (int)control.ActualHeight, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(control);
var frame = BitmapFrame.Create(bitmap);
encoder.Frames.Add(frame);
using (Stream stm = File.Create("filename.png"))
encoder.Save(stm);
However, when I try to implement this for LiveCharts2 with the following code, I'm not seeing any chart output as a PNG...
CartesianChart visual = new CartesianChart() {
// Series = series,
Height = 700,
Width = 700,
EasingFunction = null
};
var viewbox2 = new Viewbox();
viewbox2.Child = visual;
viewbox2.Measure(visual.RenderSize);
viewbox2.Arrange(new Rect(new System.Windows.Point(0, 0), visual.RenderSize));
visual.CoreChart.Update(new LiveChartsCore.Kernel.ChartUpdateParams() { IsAutomaticUpdate = false, Throttling = false });
viewbox2.UpdateLayout();
var encoder2 = new PngBitmapEncoder();
RenderTargetBitmap bmp = new(700, 700, 96, 96, PixelFormats.Pbgra32);
bmp.Render(visual);
encoder2.Frames.Add(BitmapFrame.Create(bmp));
using (Stream stm = File.Create("filename.png"))
encoder2.Save(stm);
Can anyone help fix this issue? Thanks in advance.
Found the answer here:
https://github.com/beto-rodriguez/LiveCharts2/discussions/725#discussioncomment-4030202
var skChart = new SKCartesianChart(chartControl) { Width = 900, Height = 600, };
skChart.SaveImage("CartesianImageFromControl.png");
I'm trying to generate png images from a background thread to prevent the UI from freezing up. I have a UserControl that I'm using to generate the visual. The problem is that it takes about 200ms per image, and I am unable to get it to run in the background.
To be clear I do not need to show the anything in the UI at all only generate a png to be stored in a database.
Here is the code that I tried putting in a task.
var c1 = await Task<byte[]>.Factory.StartNew(() =>
{
var _TrimDesignerVM = new TrimDesignerVM(new Profile(line.CustomTrimInfo));
_TrimDesignerVM.CanvasWidth = 520.0;
_TrimDesignerVM.CanvasHeight = 520.0;
_TrimDesignerVM.ZoomToFit();
//System.InvalidOperationException: 'The calling thread must be STA, because many UI components require this.'
var control = new Views.CustomTrimDetail(); //this is the line that throws an exception.
control.DataContext = _TrimDesignerVM;
control.Width = 742;
control.Height = 520;
control.Measure(new Size(742, 520));
control.Arrange(new Rect(new Size(742, 520)));
control.UpdateLayout();
var rect = new Rect(control.RenderSize);
var visual = new DrawingVisual();
using (var dc = visual.RenderOpen()) dc.DrawRectangle(new VisualBrush(control), null, rect);
var c = new byte[] { };
double w = 742, h = 520, dpi = 96, scale = dpi / 96;
var bitmap = new RenderTargetBitmap((int)(w * scale), (int)(h * scale), dpi, dpi, PixelFormats.Default);
bitmap.Render(visual);
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
using (MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
contents = ms.ToArray();
}
return c;
});
Is it possible to do this without freezing the UI thread?
In my WPF application I have a ScrollViewer which is dynamically populated by DataBinding and the use of a UserControl. Imagine that my UserControl is something simple that only contains a label, and the value displayed in the label comes from a list. So when I run the application it looks like below:
As you can see there are multiple instances of the UserControl each with a different value that is dynamically populated. My goal is to export each of the UserControls as a separate PNG. My EXPORT PNG button click should do this.
So I looked around and found this example which works fine for exporting the entire content of the ScorllViewer.
So I tried modifying it to achieve my goal, and I do get it to work to a certain extent, but not quite what I want.
Here's my code:
private void ExportPNG()
{
var dir = Directory.GetCurrentDirectory();
var file = "ITEM_{0}.PNG";
var height = 100.0; // Height of the UserControl
var width = mainSV.ActualWidth;
for (int i = 1; i <= ItemList.Count; i++)
{
var path = System.IO.Path.Combine(dir, string.Format(file, i));
Size size = new Size(width, height);
UIElement element = mainSV.Content as UIElement;
element.Measure(size);
element.Arrange(new Rect(new Point(0, 0), size));
RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)width, (int)height, 96, 96, PixelFormats.Pbgra32);
VisualBrush sourceBrush = new VisualBrush(element);
DrawingVisual drawingVisual = new DrawingVisual();
DrawingContext drawingContext = drawingVisual.RenderOpen();
using (drawingContext)
{
drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(width, height)));
}
renderTarget.Render(drawingVisual);
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(renderTarget));
using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write))
{
encoder.Save(stream);
}
}
}
Now this exports 5 PNGs (when my list has 5 items), bu they all contain the image of the first element:
And I figure the problem is likely where I do the drawingContext.DrawRectangle() because my rectanble coordinates are always the same. So I tried changing it to the following, which I thought should work, but for some reason it just generates one PNG with the first UserControl and 4 empty PNGs.
using (drawingContext)
{
drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, (i-1) * height), new Point(width, height + ((i-1) * height))));
}
And the result:
What am I doing wrong here?
If you would like to run the code please find it here.
Please check below two methods. I tested it and it is working very well.
1. First, find children from you Items controls
2. Convert them to PNGs.
private void ExportPNG()
{
var dir = Directory.GetCurrentDirectory();
var file = "ITEM_{0}.PNG";
var height = 100.0;
var width = 100.0;
var children = GetChildrenOfType<UCDisplayItem>(itC);
foreach (var item in children)
{
var path = System.IO.Path.Combine(dir, string.Format(file, DateTime.Now.Ticks));
Size size = new Size(width, height);
UIElement element = item as UIElement;
element.Measure(size);
element.Arrange(new Rect(new Point(0, 0), size));
RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)width, (int)height, 96, 96, PixelFormats.Pbgra32);
VisualBrush sourceBrush = new VisualBrush(element);
DrawingVisual drawingVisual = new DrawingVisual();
DrawingContext drawingContext = drawingVisual.RenderOpen();
using (drawingContext)
{
drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(width, height)));
//drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, (i - 1) * height), new Point(width, height + ((i - 1) * height))));
}
renderTarget.Render(drawingVisual);
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(renderTarget));
using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write))
{
encoder.Save(stream);
}
}
}
public List<T> GetChildrenOfType<T>( DependencyObject depObj)
where T : DependencyObject
{
var result = new List<T>();
if (depObj == null) return null;
var queue = new Queue<DependencyObject>();
queue.Enqueue(depObj);
while (queue.Count > 0)
{
var currentElement = queue.Dequeue();
var childrenCount = VisualTreeHelper.GetChildrenCount(currentElement);
for (var i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(currentElement, i);
if (child is T)
result.Add(child as T);
queue.Enqueue(child);
}
}
return result;
}
RESULT
Using this method, I want to render a canvas to a bitmap.
When I add a Shape to the Canvas, it is rendered twice the specified size.
In the example below, I am drawing a line from (0;0) to (50;50) on a canvas of size 200 by 200.
public bool exportToBmp(string path, int dpi = 96)
{
if (path == null)
return false;
var canvas = new System.Windows.Controls.Canvas();
// This diagonal Line should span a quarter of the rendered Image
var myLine = new System.Windows.Shapes.Line();
myLine.Stroke = System.Windows.Media.Brushes.LightSteelBlue;
myLine.X1 = 0;
myLine.X2 = 50;
myLine.Y1 = 0;
myLine.Y2 = 50;
myLine.StrokeThickness = 2;
canvas.Children.Add(myLine);
canvas.Height = 200;
canvas.Width = 200;
Size size = new Size(canvas.Width, canvas.Height);
canvas.Measure(size);
canvas.Arrange(new Rect(size));
var width = (int)canvas.ActualWidth;
var height = (int)canvas.ActualHeight;
RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, dpi, dpi, PixelFormats.Pbgra32);
bmp.Render(canvas);
PngBitmapEncoder image = new PngBitmapEncoder();
image.Frames.Add(BitmapFrame.Create(bmp));
using (Stream fs = File.Create(path))
{
image.Save(fs);
}
return false;
}
The rendered image I get is 200 by 200 px big, but the diagonal goes all the way to (100;100)
What am I doing wrong?
When I run your code, I see the following image (border added for clarity):
Are you passing a DPI other than 96?
What DPI settings are in use on your computer?
I have a chart that I'm displaying to the user and I want to be able to export the chart as an image to disk so they can use it outside of the application (for a presentation or something).
I've managed to get the basic idea working using PngBitmapEncoder and RenderTargetBitmap but the image I get out of it is way to small to really be usable and I want to get a much larger image.
I tried to simply increase the Height and Width of the control I was wanting to render, but the parent seems to have direct control on the render size. From this I tried to duplicate the UIElement in memory but then the render size was (0,0) and when I tried to use methods to get it to render, such as Measure() Arrange() and UpdateLayout() they throw exceptions about needing to decouple the parent to call these, but as it's in memory and not rendered there shouldn't be a parent?
This is all done with Visiblox charting API
Here is what I've got currently, except it doesn't work :(
var width = 1600;
var height = 1200;
var newChart = new Chart { Width = width, Height = height, Title = chart.Title, XAxis = chart.XAxis, YAxis = chart.YAxis, Series = chart.Series};
Debug.WriteLine(newChart.RenderSize);
var size = new Size(width, height);
newChart.Measure(size);
newChart.Arrange(new Rect(size));
newChart.UpdateLayout();
Debug.WriteLine(newChart.RenderSize);
var rtb = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
rtb.Render(newChart);
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(rtb));
using (var stream = fileDialog.OpenFile())
encoder.Save(stream);
I've gotten a bit closer, it now render the graph background the axis' etc. but just not the actual lines that are being graphed. Below is an updated source
public static void RenderChartToImage(Chart elementToRender, string filename)
{
if (elementToRender == null)
return;
Debug.Write(elementToRender.RenderSize);
var clone = new Chart();
clone.Width = clone.Height = double.NaN;
clone.HorizontalAlignment = HorizontalAlignment.Stretch;
clone.VerticalAlignment = VerticalAlignment.Stretch;
clone.Margin = new Thickness();
clone.Title = elementToRender.Title;
clone.XAxis = new DateTimeAxis();
clone.YAxis = new LinearAxis() { Range = Range<double>)elementToRender.YAxis.Range};
foreach (var series in elementToRender.Series)
{
var lineSeries = new LineSeries
{
LineStroke = (series as LineSeries).LineStroke,
DataSeries = series.DataSeries
};
clone.Series.Add(lineSeries);
}
var size = new Size(1600, 1200);
clone.Measure(size);
clone.Arrange(new Rect(size));
clone.UpdateLayout();
Debug.Write(clone.RenderSize);
var height = (int)clone.ActualHeight;
var width = (int)clone.ActualWidth;
var renderer = new RenderTargetBitmap(width, height, 96d, 96d, PixelFormats.Pbgra32);
renderer.Render(clone);
var pngEncoder = new PngBitmapEncoder();
pngEncoder.Frames.Add(BitmapFrame.Create(renderer));
using (var file = File.Create(filename))
{
pngEncoder.Save(file);
}
}
So I get out something like this:
Which while big, isn't useful as it has nothing charted.
http://www.visiblox.com/blog/2011/05/printing-visiblox-charts
The main point I was missing was
InvalidationHandler.ForceImmediateInvalidate = true;
Setting this before I rendered the chart in memory and then reverting it once I had finished. From there it was smooth sailing :D
RenderTargetBitmap DrawToImage<T>(T source, double scale) where T:FrameworkElement
{
var clone = Clone(source);
clone.Width = clone.Height = Double.NaN;
clone.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
clone.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
clone.Margin = new Thickness();
var size = new Size(source.ActualWidth * scale, source.ActualHeight * scale);
clone.Measure(size);
clone.Arrange(new Rect(size));
var renderBitmap = new RenderTargetBitmap((int)clone.ActualWidth, (int)clone.ActualHeight, 96, 96, PixelFormats.Pbgra32);
renderBitmap.Render(clone);
return renderBitmap;
}
static T Clone<T>(T source) where T:UIElement
{
if (source == null)
return null;
string xaml = XamlWriter.Save(source);
var reader = new StringReader(xaml);
var xmlReader = XmlTextReader.Create(reader, new XmlReaderSettings());
return (T)XamlReader.Load(xmlReader);
}
I think these might help :
Exporting Visifire Silverlight Chart as Image with a downloadable silverlight solution.
Exporting Chart as Image in WPF