1.0定义全局变量
string photoPath;//图片保存的位置
string stuID;//获得学生学号
2.0初始情况下判断要保存的路劲是否存在
try
{
if (!Directory.Exists(@"E:/学生党员信息管理系统/Resource/photo/"))//当该文件夹不存在时
{
//创建文件夹
Directory.CreateDirectory(@"E:/学生党员信息管理系统/Resource/photo/");
}
this.photoPath = @"E:/学生党员信息管理系统/Resource/photo/";
}
catch (IOException ioEx)
{
MessageBox.Show("初始化系统文件夹失败:", "消息");
return;
}
3.0定义一个方法弹出一个对话框供用户选择图片,
private void addPhoto()
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "JPEG(*.jpg)|*jpg";
ofd.FilterIndex = 0;
ofd.ReadOnlyChecked = false;
if (ofd.ShowDialog() == DialogResult.OK)
{
string photoPathCurrent = ofd.FileName;//获得图片绝对路径
this.pictureBox1.Image = Image.FromFile(photoPathCurrent);
//判断图片是否符合要求
if (this.pictureBox1.Image.Width <= 145 && this.pictureBox1.Image.Width > 110
&& this.pictureBox1.Image.Height <= 140 && this.pictureBox1.Image.Height > 100)
{
}
else
{
MessageBox.Show("您添加的图片不符合要求:宽110-140,高100-135,请重新添加","提示");
photoPath ="";
this.pictureBox1.Image = global ::学生党员信息管理系统.Properties.Resources.系统默认相片;
}
}
}
4.0保存图本地前面指定的文件夹,已指定的格式
private void savePhotoToFile(string savePath)
{
try
{
if (this.pictureBox1.Image != null)//在图片框中有图片的时候
{
if (savePath != "" && savePath != null)
{
this.pictureBox1.Image.Save(savePath , System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
catch (IOException ioEx)
{
MessageBox.Show("图片保存失败:" + ioEx.Message, "提示");
}
}
5.0将保存的图片显示出来
private void showPhotoFromFile(string strPath)
{
try
{
if (File.Exists(strPath))
{
//this.pictureBox1.Image = Image.FromFile(strPath);//最好不用此操作,他会一直暂用资源,无法对图片进行更新
this.pictureBox1.ImageLocation = strPath;
}
else
{
this.pictureBox1.Image = global ::学生党员信息管理系统.Properties.Resources.系统默认相片 ;
}
}
catch (IOException ioEx)
{
MessageBox.Show("加载相片失败,请检查" + @"E:/学生党员信息管理系统/Resource/photo/路径是否存在:"+ioEx .Message ,"消息");
}
}
并将用户选择的图片显示在pictureBox控件上