在 C# 控制台应用程序中,如何生成 Google Charts API 请求并将结果保存为图像?

发布于 2024-12-29 08:33:02 字数 224 浏览 5 评论 0原文

是否可以在控制台应用程序中调用 Google Charts API 并将结果保存为 JPEG 或 PNG 文件?我可以在网络应用程序中轻松完成此操作,只是不太确定如何在 C# 中完成此操作。

非常感谢

- https://chart.googleapis.com/chart

Is it possible to make a call to the Google Charts API in a console app and save the result as a JPEG or PNG file? I can do it easily in a web app, just not quite sure how to do it in C#.

Many thanks-

https://chart.googleapis.com/chart

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

↘人皮目录ツ 2025-01-05 08:33:02

您可以使用 Charts API 的 googlechartsharp 包装器获取一个网址,您可以通过该网址查看图表。

使用 HttpWebRequestHttpWebResponse 类(或根据 Joey 的回答使用 WebClient 类),您可以将响应流捕获为字节数组( image)并将其写入具有正确扩展名的文件(*.png 文件)。像这样的东西:

string chartUrl = chart.GetUrl();
byte[] chartBytes = null;
WebClient client = new WebClient();
chartBytes = client.DownloadData(chartUrl);

using (var memStream = new MemoryStream())
{
    memStream.Write(chartBytes, 0, chartBytes.Length);
}

File.WriteAllBytes("C:\temp\myChart.png", chartBytes);

You could use the googlechartsharp wrapper for the Charts API to get a URL at which you can view the chart.

Using the HttpWebRequest and HttpWebResponse classes (or the WebClient class as per Joey's answer), you could capture the response stream as a byte array (the image) and write that to a file with the proper extension (a *.png file). Something like:

string chartUrl = chart.GetUrl();
byte[] chartBytes = null;
WebClient client = new WebClient();
chartBytes = client.DownloadData(chartUrl);

using (var memStream = new MemoryStream())
{
    memStream.Write(chartBytes, 0, chartBytes.Length);
}

File.WriteAllBytes("C:\temp\myChart.png", chartBytes);
北风几吹夏 2025-01-05 08:33:02

使用 WebClient 类及其 下载数据DownloadFile 方法。构建要检索的 URL 由您决定。

Use the WebClient class and its DownloadData or DownloadFile methods. Constructing the URL to retrieve is up to you.

拥抱影子 2025-01-05 08:33:02

我添加了我的图表生成器类(工作完美)。只需调用它(如下所示)添加您自己的事件方法即可在生成图表后捕获图表并将其保存到 HDD。

调用类并生成图表:

   ChartGenerator charBartGen = new ChartGenerator();
            charBartGen.ChartCreated += new ChartCreatedEventHandler(charBartGen_ChartCreated);
            charBartGen.CreateBarChart(pictureBox2.Height, pictureBox2.Width,
                stats.MaxChecks,
                "Past 7 days",
                stats.Last7DayChecks1, stats.Last7DayChecks2);

实际类:

   public class ChartGenerator
{
    public event ChartCreatedEventHandler ChartCreated;

    public string CreatePieChartUrl(int pHeight, int pWidth,
        string[] pSeries, string pTitle, int[] pData)
    {

        string st = String.Format(Misc.EnUk,
        @"http://chart.apis.google.com/chart?chs={0}x{1}&cht=p3&chd=t:", pWidth, pHeight);
        for (int i = 0; i < pData.Length; i++)
        {
            st += pData[i].ToString(Misc.EnUk) + ",";
        }

        st = st.TrimEnd(',');

        st += "&chdl=";
        for (int i = 0; i < pData.Length; i++)
        {
            st += pSeries[i].Replace(" ", "+") + "|";
        }
        st = st.TrimEnd('|');

        st += "&chtt=";
        st += pTitle.Replace(" ", "+") + "|";

        return st;
    }

    public void CreatePieChart(int pHeight, int pWidth,
        string[] pSeries, string pTitle, int[] pData)
    {
        string url = CreatePieChartUrl(pHeight, pWidth,
         pSeries, pTitle, pData);
        Thread th = new Thread(new ParameterizedThreadStart(CreateChartAsync));
        th.Start(url);
    }

    public string CreateBarChartUrl(int pHeight, int pWidth, int pMax,
        string pTitle, int[] pData1, int[] pData2)
    {
      string st = String.Format(Misc.EnUk,
        @"http://chart.apis.google.com/chart?chxr=0,0,{0}&chxt=y&chbh=a&chs={1}x{2}&cht=bvs&chco=4D89F9,C6D9FD&chds=0,{0},0,{0}&chd=t:", 
            pMax, pWidth, pHeight);

        for (int i = 0; i < pData1.Length; i++)
        {
            st += pData1[i].ToString(Misc.EnUk) + ",";
        }
        st = st.TrimEnd(',');
        st += "|";

        for (int i = 0; i < pData2.Length; i++)
        {
            st += pData2[i].ToString(Misc.EnUk) + ",";
        }
        st = st.TrimEnd(',');

        st += "&chtt=";
        st += pTitle.Replace(" ", "+");

        return st;
    }

    public void CreateBarChart(int pHeight, int pWidth,int pMax,
      string pTitle, int[] pData1,int[] pData2)
    {
        string url = CreateBarChartUrl(pHeight, pWidth, pMax,
        pTitle, pData1, pData2);
        Thread th = new Thread(new ParameterizedThreadStart(CreateChartAsync));
        th.Start(url);
    }

    private void CreateChartAsync(object pUrl)
    {
        string url = pUrl as string;

        try
        {
            if (url != null)
            {
                using (Stream stream = GetPageContentStream(url, false))
                {
                    Image img = Image.FromStream(stream);

                    if (img != null)
                    {
                        if (ChartCreated != null)
                        {
                            ChartCreated(this, new ChartCreatedEventArgs(img));
                        }
                    }
                }
            }
        }
        catch (Exception err)
        {
            Debug.Fail(err.Message);
        }
    }

    /// <summary>
    /// Gets the stream of the given url
    /// </summary>
    /// <param name="url">The url</param>
    /// <param name="file">Whether this is a web file stream or a HttpWebRequest</param>
    /// <returns></returns>
    public static Stream GetPageContentStream(string url, bool file)
    {
        try
        {
            WebRequest wreq;
            WebResponse wres;

            if (file)
            {
                wreq = System.Net.FileWebRequest.Create(url);
            }
            else
            {
                wreq = HttpWebRequest.Create(url);
                HttpWebRequest httpwrqst = wreq as HttpWebRequest;

                if (httpwrqst != null)
                {
                    httpwrqst.AllowAutoRedirect = false;
                    httpwrqst.Timeout = 10000;
                }
            }

            wres = wreq.GetResponse();
            return wres.GetResponseStream();
        }
        catch(Exception err)
        {
            Debug.Fail(err.Message);
            Logger.AppLogger.Instance.LogError("GetPageContentStream", err);
            return null;
        }
    }

}

public delegate void ChartCreatedEventHandler(object sender,ChartCreatedEventArgs e);

[Serializable]
public class ChartCreatedEventArgs : EventArgs
{
    private readonly Image mImage;

    public ChartCreatedEventArgs()
    {
    }

    public ChartCreatedEventArgs(Image pImage)
    {
        mImage = pImage;
    }

    public Image Image
    {
        get
        {
            return mImage;
        }
    }

}

I added my Chart generator class (working perfectly). Just call it (as seen below) add your own event method to catch the chart once it is generated and save it to the HDD.

Calling the class and generating the chart:

   ChartGenerator charBartGen = new ChartGenerator();
            charBartGen.ChartCreated += new ChartCreatedEventHandler(charBartGen_ChartCreated);
            charBartGen.CreateBarChart(pictureBox2.Height, pictureBox2.Width,
                stats.MaxChecks,
                "Past 7 days",
                stats.Last7DayChecks1, stats.Last7DayChecks2);

The actual class:

   public class ChartGenerator
{
    public event ChartCreatedEventHandler ChartCreated;

    public string CreatePieChartUrl(int pHeight, int pWidth,
        string[] pSeries, string pTitle, int[] pData)
    {

        string st = String.Format(Misc.EnUk,
        @"http://chart.apis.google.com/chart?chs={0}x{1}&cht=p3&chd=t:", pWidth, pHeight);
        for (int i = 0; i < pData.Length; i++)
        {
            st += pData[i].ToString(Misc.EnUk) + ",";
        }

        st = st.TrimEnd(',');

        st += "&chdl=";
        for (int i = 0; i < pData.Length; i++)
        {
            st += pSeries[i].Replace(" ", "+") + "|";
        }
        st = st.TrimEnd('|');

        st += "&chtt=";
        st += pTitle.Replace(" ", "+") + "|";

        return st;
    }

    public void CreatePieChart(int pHeight, int pWidth,
        string[] pSeries, string pTitle, int[] pData)
    {
        string url = CreatePieChartUrl(pHeight, pWidth,
         pSeries, pTitle, pData);
        Thread th = new Thread(new ParameterizedThreadStart(CreateChartAsync));
        th.Start(url);
    }

    public string CreateBarChartUrl(int pHeight, int pWidth, int pMax,
        string pTitle, int[] pData1, int[] pData2)
    {
      string st = String.Format(Misc.EnUk,
        @"http://chart.apis.google.com/chart?chxr=0,0,{0}&chxt=y&chbh=a&chs={1}x{2}&cht=bvs&chco=4D89F9,C6D9FD&chds=0,{0},0,{0}&chd=t:", 
            pMax, pWidth, pHeight);

        for (int i = 0; i < pData1.Length; i++)
        {
            st += pData1[i].ToString(Misc.EnUk) + ",";
        }
        st = st.TrimEnd(',');
        st += "|";

        for (int i = 0; i < pData2.Length; i++)
        {
            st += pData2[i].ToString(Misc.EnUk) + ",";
        }
        st = st.TrimEnd(',');

        st += "&chtt=";
        st += pTitle.Replace(" ", "+");

        return st;
    }

    public void CreateBarChart(int pHeight, int pWidth,int pMax,
      string pTitle, int[] pData1,int[] pData2)
    {
        string url = CreateBarChartUrl(pHeight, pWidth, pMax,
        pTitle, pData1, pData2);
        Thread th = new Thread(new ParameterizedThreadStart(CreateChartAsync));
        th.Start(url);
    }

    private void CreateChartAsync(object pUrl)
    {
        string url = pUrl as string;

        try
        {
            if (url != null)
            {
                using (Stream stream = GetPageContentStream(url, false))
                {
                    Image img = Image.FromStream(stream);

                    if (img != null)
                    {
                        if (ChartCreated != null)
                        {
                            ChartCreated(this, new ChartCreatedEventArgs(img));
                        }
                    }
                }
            }
        }
        catch (Exception err)
        {
            Debug.Fail(err.Message);
        }
    }

    /// <summary>
    /// Gets the stream of the given url
    /// </summary>
    /// <param name="url">The url</param>
    /// <param name="file">Whether this is a web file stream or a HttpWebRequest</param>
    /// <returns></returns>
    public static Stream GetPageContentStream(string url, bool file)
    {
        try
        {
            WebRequest wreq;
            WebResponse wres;

            if (file)
            {
                wreq = System.Net.FileWebRequest.Create(url);
            }
            else
            {
                wreq = HttpWebRequest.Create(url);
                HttpWebRequest httpwrqst = wreq as HttpWebRequest;

                if (httpwrqst != null)
                {
                    httpwrqst.AllowAutoRedirect = false;
                    httpwrqst.Timeout = 10000;
                }
            }

            wres = wreq.GetResponse();
            return wres.GetResponseStream();
        }
        catch(Exception err)
        {
            Debug.Fail(err.Message);
            Logger.AppLogger.Instance.LogError("GetPageContentStream", err);
            return null;
        }
    }

}

public delegate void ChartCreatedEventHandler(object sender,ChartCreatedEventArgs e);

[Serializable]
public class ChartCreatedEventArgs : EventArgs
{
    private readonly Image mImage;

    public ChartCreatedEventArgs()
    {
    }

    public ChartCreatedEventArgs(Image pImage)
    {
        mImage = pImage;
    }

    public Image Image
    {
        get
        {
            return mImage;
        }
    }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文