Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Image with Microsoft .NET Chart Controls Library without Control

Tags:

Is it possible to generate images (jpeg, png, etc) using the Microsoft Chart Controls library without instantiating a WinForm or ASP.NET Control class? All the examples I have seen utilize a control component. I need to create a library which contains simple methods that take data to be plotted and returns a new chart image. Examples:

public byte[] GeneratePlot(IList<SeriesData> series) {     // generate and return JPEG } public void GeneratePlot(IList<SeriesData> series, Stream outputStream) {     // generate JPEG and write to stream } 

If it is not possible:

  1. would you recommend creating/disposing a new chart control each time the user calls the GeneratePlot() method?
  2. is there another .NET library (preferably free) that you would recommend?

Thanks

like image 748
dewald Avatar asked Dec 01 '09 03:12

dewald


2 Answers

Yes, that's possible:

using System.Windows.Forms.DataVisualization.Charting; using System.IO; ...     public void GeneratePlot(IList<DataPoint> series, Stream outputStream) {       using (var ch = new Chart()) {         ch.ChartAreas.Add(new ChartArea());         var s = new Series();         foreach (var pnt in series) s.Points.Add(pnt);         ch.Series.Add(s);         ch.SaveImage(outputStream, ChartImageFormat.Jpeg);       }     } 
like image 110
Hans Passant Avatar answered Sep 19 '22 17:09

Hans Passant


If all you want is chart images. Then you can use the chart controls to save to disk.

myChart.SaveImage("C:\mypic.png", System.Drawing.Imaging.ImageFormat.Png) 

Then load that image from the disk. If the charts are only generated once then you can also just check the filesystem for the image first and then only re-render it if it doesnt exist.

Hope this helps.

like image 25
Leigh S Avatar answered Sep 18 '22 17:09

Leigh S