Winfrom开发之OpenFileDialog选中图片即时保存至项目中

openFileDialog1.Filter = "图片|*.*";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
Image img = Image.FromFile(openFileDialog1.FileName);
//文件名
string filename = openFileDialog1.FileName.Substring(openFileDialog1.FileName.LastIndexOf("\\") + 1);
//文件保存文件夹路径,此处【 Application.StartupPath 】就是根目录
//string savepath = Application.StartupPath + "\\img\\";
#region 保存路径为项目的根目录,从debug目录往上截取两级文件夹
string rootpath = Application.StartupPath.Substring(0, Application.StartupPath.LastIndexOf("\\"));
rootpath = rootpath.Substring(0, rootpath.LastIndexOf("\\"));
//文件保存文件夹路径
string savepath = rootpath + "\\img\\";
#endregion
//文件保存路径+文件名
string imgSavepath = savepath + filename;

//判断是否存在img文件夹
if (Directory.Exists(savepath))
{
//存在img文件夹
//判断该路径下是否已经存在同名文件
if (File.Exists(imgSavepath))
{
//提示是否覆盖
if (DialogResult.Yes != MessageBox.Show("图片已存在!", "该图片已存在,是否覆盖原图片?", MessageBoxButtons.YesNo))
{
//点击【否】,返回,取消操作。
return;
}
}
}
else
{
//不存在,在根目录下创建img文件夹
Directory.CreateDirectory(savepath);
}
try
{
Image im = img;
Bitmap bit = new Bitmap(im);
bit.Save(imgSavepath, System.Drawing.Imaging.ImageFormat.Bmp);
MessageBox.Show("图片保存成功!");
}
catch{}

posted @ 2018-07-16 16:42  新自己  阅读(495)  评论(0编辑  收藏  举报