0
單擊按鈕時,我想要將圖表另存爲帶保存文件對話框的圖像。我的應用程序類型是c#Windows窗體應用程序。因此,用戶可以將圖像文件保存在他/她希望的任何目錄中。如何在C#窗體應用程序中使用保存文件對話框將圖表另存爲圖像
單擊按鈕時,我想要將圖表另存爲帶保存文件對話框的圖像。我的應用程序類型是c#Windows窗體應用程序。因此,用戶可以將圖像文件保存在他/她希望的任何目錄中。如何在C#窗體應用程序中使用保存文件對話框將圖表另存爲圖像
我已經做出瞭解決方法:使用字典文件擴展名
private void exportAsImagebtn_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "PNG Image|*.png|JPeg Image|*.jpg";
saveFileDialog.Title = "Save Chart As Image File";
saveFileDialog.FileName = "Sample.png";
DialogResult result = saveFileDialog.ShowDialog();
saveFileDialog.RestoreDirectory = true;
if (result == DialogResult.OK && saveFileDialog.FileName != "")
{
try
{
if (saveFileDialog.CheckPathExists)
{
if (saveFileDialog.FilterIndex == 2)
{
chart.SaveImage(saveFileDialog.FileName, ChartImageFormat.Jpeg);
}
else if (saveFileDialog.FilterIndex == 1)
{
chart.SaveImage(saveFileDialog.FileName, ChartImageFormat.Png);
}
}
else
{
MessageBox.Show("Given Path does not exist");
}
}
catch(Exception ex){
MessageBox.Show(ex.Message);
}
}
}
或者這樣:
try
{
//Check if chart has at least one enabled series with points
if (chart1.Series.Any(s => s.Enabled && s.Points.Count>0))
{
SaveFileDialog save = new SaveFileDialog();
save.Filter = "Image Files|*.png;";
save.Filter = "Bitmap Image (.bmp)|*.bmp|Gif Image (.gif)|*.gif|JPEG Image (.jpeg)|*.jpeg|Png Image (.png)|*.png|Tiff Image (.tiff)|*.tiff";
save.Title = "Save Chart Image As file";
save.DefaultExt = ".png";
if (save.ShowDialog() == DialogResult.OK)
{
var imgFormats = new Dictionary<string, ChartImageFormat>()
{
{".bmp", ChartImageFormat.Bmp},
{".gif", ChartImageFormat.Gif},
{".jpg", ChartImageFormat.Jpeg},
{".jpeg", ChartImageFormat.Jpeg},
{".png", ChartImageFormat.Png},
{".tiff", ChartImageFormat.Tiff},
};
var fileExt = System.IO.Path.GetExtension(save.FileName).ToString().ToLower();
if (imgFormats.ContainsKey(fileExt))
{
chart1.SaveImage(save.FileName, imgFormats[fileExt]);
}
else
{
throw new Exception(String.Format("Only image formats '{0}' supported", string.Join(", ", imgFormats.Keys)));
}
}
}
else
{
throw new Exception("Nothing to export");
}
}
catch (Exception ex)
{
MessageBox.Show("SaveChartAsImage()", ex.Message);
}