Profile

Click to view full profile
Hi, I'm Veerapat Sriarunrungrueang, an expert in technology field, especially full stack web development and performance testing.This is my coding diary. I usually develop and keep code snippets or some tricks, and update to this diary when I have time. Nowadays, I've been giving counsel to many well-known firms in Thailand.
view more...

Thursday, September 13, 2012

Get Dynamic Image in string format from Post Ajax Services

Instead of loading images via provided links, we can send images directly, and request it from ajax post channel. In order to do that, first covert image into array of bytes, then transform them into string base 64.
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