For example:
public JsonResult GetImage(string chartname) { var chart = new Chart(); chart.ChartAreas.Add(new ChartArea()); var series = new Series(chartname); series.ChartType = SeriesChartType.Line; series.Points.AddXY(1, 1); series.Points.AddXY(2, 2); series.Points.AddXY(3, 3); chart.Series.Add(series); string result = null; byte[] bytes = null; using (MemoryStream stream = new MemoryStream()) { chart.SaveImage(stream, ChartImageFormat.Png); bytes = stream.ToArray(); result = Convert.ToBase64String(bytes); } return Json(result); }This example will convert chart image into PNG binary file format then convert to string base 64 before return.
For the client side, just write ajax post method, after get data insert image element into somewhere on a page.
For example:
<!DOCTYPE html> <html> <head> <title>Image Service Index</title> <script type="text/javascript"> function load() { $.ajax({ type: "POST", data: { "chartname": "ImageServiceTest" }, url: "@Url.Action("GetImage", "ImageService")", dataType: "json", success: function (response) { var chartDivId = $('#imageContent'); // Response message will be json format if we use json as a data type $(chartDivId).html('<img src="data:image/png;base64,' + response + '" />'); }, error: function (ex) { debugger; alert(ex.status); } }); } window.onload = load; </script> </head> <body> <div id="imageContent"> </div> </body> </html>You can download full example here.
P.S. This example use ASP.NET MVC 3 for the server side, and use jQuery in the client side.
No comments:
Post a Comment