Search code examples
c#csvjpegmschart

How to plotted graph save as a JPEG image in C#


I want to save my plotted graph as a JPEG image by clicking save button.Please give me to help for solving this.this is my plotted grapg look like.my plotted graph area

This is code that I used to plotted the graph.

 private void Output_Load(object sender, EventArgs e)
        {

            List<Graph> ObservingData = new List<Graph>(); // List to store all available Graph objects from the CSV

            // Loops through each lines in the CSV
            foreach (string line in System.IO.File.ReadAllLines(pathToCsv).Skip(1)) // .Skip(1) is for skipping header
            {
                // here line stands for each line in the csv file

                string[] InCsvLine = line.Split(',');

                // creating an object of type Graph based on the each csv line

                Graph Inst1 = new Graph();


                Inst1.AvI = double.Parse(InCsvLine[1]);
                Inst1.AvE = double.Parse(InCsvLine[2]);

                chart1.Series["Speed"].YAxisType = AxisType.Primary;
                chart1.Series["Speed"].Points.AddXY(Inst1.Date.AvI, Inst1.AvE);
                chart1.Series["Speed"].ChartType = SeriesChartType.FastLine;

            }
        }

This is my part of .csv file data as follows;

Name,AvI,AvE,Test
Amal,3.28000,100,TRUE
Kamal,3.30000,150,FALSE
Ann,3.32000,200,FALSE
Jery,3.34000,220,FALSE
TaW,3.39000,130,FALSE
Nane,3.40000,125,TRUE
Petter,3.42000,300,TRUE
Sam,3.46000,265,TRUE
Daniyel,3.50000,245,TRUE
Don,3.62000,146,FALSE
Zip,3.64000,201,FALSE
Sera,3.68000,300,FALSE
Perera,3.70000,200,TRUE
Dam,3.90000,170,TRUE

Solution

  • Here is an example with using the SaveFileDialog and outputting the chart as a png image.

    private void buttonSave_Click(object sender, EventArgs e)
    {
        try
        {
            string path;
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Png Image (.png)|*.png";
    
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                path = sfd.FileName;
    
                if (!string.IsNullOrEmpty(path))
                {
                    chart1.SaveImage(path, ChartImageFormat.Png);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }