Save Chart Image To Server In ASP.NET

Let’s start this blog.

First, we create an MVC project.
 
Go to File-> New-> Project and select “ASP.NET Web Application”.
 
 
Enter the Project name and give a path in Location, after it clicks on ok button.
 
 
Add below URLs in the view page
  1. <script src="https://www.amcharts.com/lib/3/amcharts.js"></script>    
  2. <script src="https://www.amcharts.com/lib/3/pie.js"></script>    
  3. <script src="https://www.amcharts.com/lib/3/plugins/export/export.min.js"></script>    
  4. <link rel="stylesheet" href="https://www.amcharts.com/lib/3/plugins/export/export.css" type="text/css" media="all" />    
  5. <script src="https://www.amcharts.com/lib/3/themes/light.js"></script>    
Copy below code into view where you want to display the chart.
  1. @{  
  2.     ViewBag.Title = "Home Page";  
  3. }  

  4.   
  5. <style>  
  6.   
  7. #MyChart{  
  8.   width: 100%;  
  9.   height: 500px;  
  10. }  
  11.   
  12. #exportChart {  
  13.   font-size: 18px;  
  14.   padding: 5px 10px;  
  15.   position: absolute;  
  16.   top: 30px;  
  17.   right: 30px;  
  18.   z-index: 10;  
  19. }  
  20. </style>  
  21.   
  22. <div id="MyChart" style="width:50%"></div>  
  23. <br />  
  24.   
  25. <input type="button" id="exportChart" value="Export Chart" onclick="exportChart();" />  
  26.   
  27.   
  28. <script>  
  29.     var chart = AmCharts.makeChart("MyChart", {  
  30.         "type""pie",  
  31.         "theme""light",  
  32.         "dataProvider": [{  
  33.             "City""Surat",  
  34.             "litres": 501.9  
  35.         }, {  
  36.             "City""Karnavati",  
  37.             "litres": 301.9  
  38.         }, {  
  39.             "City""Navsari",  
  40.             "litres": 201.1  
  41.         }, {  
  42.             "City""Junagadh",  
  43.             "litres": 165.8  
  44.         }, {  
  45.             "City""Amreli",  
  46.             "litres": 139.9  
  47.         }, {  
  48.             "City""Bhavnagar",  
  49.             "litres": 128.3  
  50.         }, {  
  51.             "City""Gondal",  
  52.             "litres": 99  
  53.         }, {  
  54.             "City""Rajkot",  
  55.             "litres": 60  
  56.         }, {  
  57.             "City""Pune",  
  58.             "litres": 50  
  59.         }],  
  60.         "valueField""litres",  
  61.         "titleField""City",  
  62.         "balloon": {  
  63.             "fixedPosition"true  
  64.         },  
  65.         "export": {  
  66.             "enabled"true,  
  67.             "menu": []  
  68.         }  
  69.     });  
  70.   
  71.     function exportChart() {  
  72.         chart["export"].capture({}, function () {  
  73.   
  74.             this.toPNG({}, function (base64) {  
  75.   
  76.                 $.ajax({  
  77.                     url: '/Home/SaveImage',  
  78.                     type: 'POST',  
  79.                     data: { base64: base64},  
  80.                     success: function (data) {  
  81.                         if (data != "") {  
  82.                             alert("file saved.")  
  83.                         }  
  84.                         else {  
  85.                             alert("file not saved.")  
  86.                         }  
  87.                     },  
  88.                     error: function (r, s, e) {  
  89.                         alert("Unexpected error:" + e);  
  90.                         console.log(r);  
  91.                         console.log(s);  
  92.                         console.log(e);  
  93.                     }  
  94.                 });  
  95.                   
  96.             });  
  97.         });  
  98.     }  
  99.   
  100.       
  101. </script>  
Now copy and paste below function into your Home controller.
  1. [HttpPost]  
  2.        public JsonResult SaveImage(string base64)  
  3.        {  
  4.            string filePath = "";  
  5.              
  6.            string FileName = string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now);  
  7.            string DomainName = ConfigurationSettings.AppSettings["DomainName"];  
  8.   
  9.            try  
  10.            {  
  11.                var imageParts = base64.Split(',').ToList<string>();  
  12.                  
  13.                byte[] Image = Convert.FromBase64String(imageParts[1]);  
  14.                  
  15.                filePath = System.Web.Hosting.HostingEnvironment.MapPath("~/Image/" + FileName + ".png");  
  16.                System.IO.File.WriteAllBytes(filePath, Image);  
  17.                filePath = DomainName + "Image/" + FileName + ".png";  
  18.   
  19.            }  
  20.            catch (Exception ex)  
  21.            {  
  22.                filePath = "";  
  23.            }  
  24.   
  25.            return Json(filePath, JsonRequestBehavior.AllowGet);  
  26.        }  

In this SaveImage() function, we get the base64 as a string from parameter and convert it to png using convert the base64 to bytes.

For getting the domain name in this article we use the "ConfigurationSettings.AppSettings["DomainName"]"

So, you need to add the "DomainName" key into the web.config like below code.
  1. <add key="DomainName" value="http://localhost:42213//" />  
Right now I'm running my local project so I give the value of localhost but you can add your live domain name and don't forget to give permission to the folder for read and write for save image.
 
Output