C# 使用 Microsoft .NET Chart Controls Library 生成图像,无需控制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1823884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generate Image with Microsoft .NET Chart Controls Library without Control
提问by dewald
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:
是否可以在不实例化 WinForm 或 ASP.NET 控件类的情况下使用 Microsoft 图表控件库生成图像(jpeg、png 等)?我见过的所有例子都使用了一个控制组件。我需要创建一个库,其中包含用于绘制数据并返回新图表图像的简单方法。例子:
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:
如果不可能:
- would you recommend creating/disposing a new chart control each time the user calls the GeneratePlot() method?
- is there another .NET library (preferably free) that you would recommend?
- 每次用户调用 GeneratePlot() 方法时,您是否建议创建/处理一个新的图表控件?
- 您是否会推荐另一个 .NET 库(最好是免费的)?
Thanks
谢谢
采纳答案by Hans Passant
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);
}
}
回答by Leigh S
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.
希望这可以帮助。