单击按钮时,我想将图表另存为带有保存文件对话框的图像。我的应用程序类型是c#Windows Forms Application。这样用户就可以将图像文件保存在他/她希望的任何目录中。
答案 0 :(得分:2)
我做了一个工作:
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);
}
}
}
答案 1 :(得分:0)
或者像这样使用字典扩展文件:
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);
}