OpenFileDialog和SaveFileDialog的简单使用
Posted 阚金翔
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了OpenFileDialog和SaveFileDialog的简单使用相关的知识,希望对你有一定的参考价值。
//文件名
private string curFileName;
//图像对象1
private Bitmap curBitmap;
//将本地图片保存到pictureBox中
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog opnDlg = new OpenFileDialog();
opnDlg.Filter = "所有图像文件 | *.bmp; *.pcx; *.png; *.jpg; *.gif;" +
"*.tif; *.ico; *.dxf; *.cgm; *.cdr; *.wmf; *.eps; *.emf|" +
"位图( *.bmp; *.jpg; *.png;...) | *.bmp; *.pcx; *.png; *.jpg; *.gif; *.tif; *.ico|" +
"矢量图( *.wmf; *.eps; *.emf;...) | *.dxf; *.cgm; *.cdr; *.wmf; *.eps; *.emf";
opnDlg.Title = "打开图像文件";
opnDlg.ShowHelp = true;
if (opnDlg.ShowDialog() == DialogResult.OK)
{
curFileName = opnDlg.FileName;
try
{
curBitmap = (Bitmap)Image.FromFile(curFileName);
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
finally
{
pictureBox1.BackgroundImage = curBitmap;
}
}
//对窗体进行重新绘制,这将强制执行paint事件处理程序
Invalidate();
}
//将pictureBox中图片保存到本地
private void button2_Click(object sender, EventArgs e)
{
//图像对象2
Bitmap curBitmap2 = (Bitmap)pictureBox1.BackgroundImage;
if (curBitmap2 == null)
{
return;
}
SaveFileDialog saveDlg = new SaveFileDialog();
saveDlg.Title = "保存为";
saveDlg.OverwritePrompt = true;
saveDlg.Filter =
"BMP文件 (*.bmp) | *.bmp|" +
"Gif文件 (*.gif) | *.gif|" +
"JPEG文件 (*.jpg) | *.jpg|" +
"PNG文件 (*.png) | *.png";
saveDlg.ShowHelp = true;
if (saveDlg.ShowDialog() == DialogResult.OK)
{
string fileName = saveDlg.FileName;
string strFilExtn = fileName.Remove(0, fileName.Length - 3);
switch (strFilExtn)
{
case "bmp":
curBitmap2.Save(fileName, System.Drawing.Imaging.ImageFormat.Bmp);
break;
case "jpg":
curBitmap2.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
break;
case "gif":
curBitmap2.Save(fileName, System.Drawing.Imaging.ImageFormat.Gif);
break;
case "tif":
curBitmap2.Save(fileName, System.Drawing.Imaging.ImageFormat.Tiff);
break;
case "png":
curBitmap2.Save(fileName, System.Drawing.Imaging.ImageFormat.Png);
break;
default:
break;
}
}
}
----------------------------------------------------------------------------
创建于2017年1月11日
整理于2017年11月29日
以上是关于OpenFileDialog和SaveFileDialog的简单使用的主要内容,如果未能解决你的问题,请参考以下文章
C# - 如何自定义 OpenFileDialog 以选择多个文件夹和文件?