Export the AmChart In Folder In ASP.NET MVC

Here, we will learn how to save the charts in the folder on export the chart in ASP.NET MVC 5. Charts are very useful for seeing how much work is done in any place in a short time of period.

Prerequisites

  • Basic knowledge of jQuery.
  • Basic Mvc.Net knowledge.
  • Data from which we can generate the charts.

Create a new project in ASP.NET MVC.

We are going to use the following jQuery libraries provided by amCharts.

<script src="https://www.amcharts.com/lib/4/core.js"></script>
<script src="https://www.amcharts.com/lib/4/charts.js"></script>
<script src="https://www.amcharts.com/lib/4/plugins/forceDirected.js"></script>
<script src="https://www.amcharts.com/lib/4/themes/animated.js"></script>

 

Open the View -> Home -> Index.cshtml and write the code for generating the chart.

@{
    ViewBag.Title = "Index";
}
<style>
    body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
}

#chartdiv {
  width: 100%;
  height: 300px;
}

input {
  position: absolute;
  top: 2em;
  right: 2em;
  padding: 1em 2em;
}


</style>

<div id="chartdiv"></div>
<input type="button" value="Export PNG" onclick="exportPNG();" />


<script src="//www.amcharts.com/lib/4/core.js"></script>
<script src="//www.amcharts.com/lib/4/charts.js"></script>

<script>


    // Create chart instance
    var chart = am4core.create("chartdiv", am4charts.XYChart);

    // Add data
    chart.data = [{
        "category": "1",
        "value": 8.5
    }, {
        "category": "1.5",
        "value": 14
    }, {
        "category": "2",
        "value": 18.5
    }, {
        "category": "2.5",
        "value": 22
    }, {
        "category": "3",
        "value": 30
    }
    , {
        "category": "4",
        "value": 40
    }, {
        "category": "5",
        "value": 50
    }];

    // Create axes
    let categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());
    categoryAxis.dataFields.category = "category";

    let valueAxis = chart.yAxes.push(new am4charts.ValueAxis());

    // Create series
    var series = chart.series.push(new am4charts.ColumnSeries());
    series.dataFields.valueY = "value";
    series.dataFields.categoryX = "category";
    series.name = "Sales";

    // Custom export function
    function exportPNG() {
        
        chart.exporting.getImage("png").then(function (imgData) {
            $.ajax({
                url: '/Home/SaveImage',
                type: 'POST',
                data: { base64: imgData },
                success: function (data) {
                    if (data != "") {
                        alert("file saved.")
                    }
                    else {
                        alert("file not saved.")
                    }
                    // do something here.
                },
                error: function (r, s, e) {
                    alert("Unexpected error:" + e);
                    console.log(r);
                    console.log(s);
                    console.log(e);
                }
            });
        });
    }

    var options = chart.exporting.getFormatOptions("png");
    options.keepTainted = true;
    chart.exporting.setFormatOptions("png", options);


    
</script>

 

put the below code into a Home controller for save the chart image into a specific folder.

[HttpPost]
      public JsonResult SaveImage(string base64)
      {
          string filePath = "";
          
          string FileName = string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now);
          string DomainName = ConfigurationSettings.AppSettings["DomainName"];

          try
          {
              var imageParts = base64.Split(',').ToList<string>();
              
              byte[] imageBytes = Convert.FromBase64String(imageParts[1]);


              MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
              // Convert byte[] to Image
              ms.Write(imageBytes, 0, imageBytes.Length);
              Image image = Image.FromStream(ms, true);

              using (var newImage = new Bitmap(800,800))
              using (var graphics = Graphics.FromImage(newImage))
              using (var stream = new MemoryStream())
              {
                  graphics.SmoothingMode = SmoothingMode.AntiAlias;
                  graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                  graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                  graphics.DrawImage(image, new Rectangle(0, 0, 800, 800));
                  newImage.Save(stream, ImageFormat.Png);
                  //return File(stream.ToArray(), "image/png");
                  byte[] bytes = stream.ToArray();
                  filePath = System.Web.Hosting.HostingEnvironment.MapPath("~/Image/" + FileName + ".png");
                  System.IO.File.WriteAllBytes(filePath, bytes);
                  filePath = DomainName + "Image/" + FileName + ".png";
              }
          }
          catch (Exception ex)
          {
              filePath = "";
          }



          return Json(filePath, JsonRequestBehavior.AllowGet);
      }

 

In this action pass the images as Base64  formate it converts the base64 to the image file and saves into a specific folder.

Please add a Domain Key in the web.config into appSetting tag like below.

<add key="DomainName" value="http://localhost:42213//" />

 

Output:

AmChart

1 Comment

  1. Hairstyles

    I have not checked in here for some time as I thought it was getting boring, but the last few posts are good quality so I guess I抣l add you back to my daily bloglist. You deserve it my friend 🙂

    0
    0
    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories