1. 程式人生 > >Winfrom開發之OpenFileDialog選中圖片即時保存至項目中

Winfrom開發之OpenFileDialog選中圖片即時保存至項目中

reat ext mage 圖片 ref link-to ogre try nal

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{}

Winfrom開發之OpenFileDialog選中圖片即時保存至項目中