所以实现图表转图片可以分一下几步走.
一.写一份WPF客户端程序
思路很简单
1.1定义一个定时器,然后检测某目录的xml文件,这里暂定目录名字为chart
- timer = new DispatcherTimer();
- timer.Interval = new TimeSpan(0, 0, 2);
- timer.Tick += new EventHandler(timer_Tick);
- timer.Start();
- void timer_Tick(object sender, EventArgs e)
- {
- string[] files = System.IO.Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "chart");
- if (files.Length > 0)
- {
- }
- }
1.2如果有的话,则进行反序列化成Chart对象进行呈现
- void timer_Tick(object sender, EventArgs e)
- {
- string[] files = System.IO.Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "chart");
- if (files.Length > 0)
- {
- LoadXml(files[0]);
- }
- }
- private void LoadXml(string xmlFile)
- {
- XmlDocument doc = new XmlDocument();
- doc.Load(xmlFile);
- StringReader stringReader = new StringReader(doc.InnerXml);
- XmlReader xmlReader = XmlReader.Create(stringReader);
- Chart chart = XamlReader.Load(xmlReader) as Chart;
- chart.AnimationEnabled = false;
- stringReader.Close();
- xmlReader.Close();
- this.Content=chart;
- }
1.3呈现好以后进行截图
- void timer_Tick(object sender, EventArgs e)
- {
- string[] files = System.IO.Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "chart");
- if (files.Length > 0)
- {
- LoadXml(files[0]);
- PrintPicture(files[0]);
- }
- }
- private void PrintPicture(string fileName)
- {
- this.Dispatcher.BeginInvoke(new Action(() =>
- {
- int Height = (int)this.ActualHeight;
- int Width = (int)this.ActualWidth;
- RenderTargetBitmap bmp = new RenderTargetBitmap(Width, Height, 96, 96, PixelFormats.Pbgra32);
- bmp.Render(this);
- string file = "C:\\temp\\a.jpg";
- BitmapEncoder encoder;
- encoder = new JpegBitmapEncoder();
- encoder.Frames.Add(BitmapFrame.Create(bmp));
- using (Stream stm = File.Create(file))
- {
- encoder.Save(stm);
- }
- File.Delete(fileName);
- }), System.Windows.Threading.DispatcherPriority.Render);
- }
1.4转换成图片完毕则删除此xml文件
二.将编译好的wpf程序放置在web根目录,然后启动此程序
三.使用ajax交互将当前显示出来的xml传送到chart目录下
前端
- $.ajax({
- type: "POST",
- url: "ajaxServer.aspx",
- data: "name=" + vChart.dataUri,
- success: function(msg) {
- alert("Success");
- }
- });
后端
拷贝xml文件或者其他处理方式把xml弄到chart目录下
- protected void Page_Load(object sender, EventArgs e)
- {
- File.Copy(Server.MapPath(this.Request["name"]), Server.MapPath("../chart/" + this.Request["name"]));
- }
注意点:转换的时候注意wpf和silverlight的命名空间.也算是一个方法,对付图表生成图片是绰绰有余的.小技巧分享一下
【编辑推荐】