图片上传到数据库
图片以二进制的形式传到数据库,具体图片文件会放到一个指定的Image文件夹
1、先上传到界面上
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//PictureBox控件显示图片
picPhoto.Load(openFileDialog1.FileName);
//获取用户选择文件的后缀名
string extension = Path.GetExtension(openFileDialog1.FileName);
//声明允许的后缀名
string[] str = new string[] { ".gif", ".jpge", ".jpg", ".png" };
if (!str.Contains(extension))
{
MessageBox.Show("仅能上传gif,jpge,jpg格式的图片!");
}
else
{
//获取用户选择的文件,并判断文件大小不能超过20K,fileInfo.Length是以字节为单位的
FileInfo fileInfo = new FileInfo(openFileDialog1.FileName);
if (fileInfo.Length > 20480)
{
MessageBox.Show("照片上传成功!");
}
else
{
//绝对路径
string image = openFileDialog1.FileName;
// 是指XXX.jpg
string picpath = openFileDialog1.SafeFileName;
File.Copy(openFileDialog1.FileName, Application.StartupPath + "\\Image\\" + picpath);
}
}
}
2、然后获取图片转换成二进制放到数据库
//获取当前选择的图片
this.picPhoto.Image = Image.FromStream(this.openFileDialog1.OpenFile());
//获取当前图片的路径
string path = openFileDialog1.FileName.ToString();
//将制定路径的图片添加到FileStream类中
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
//通过FileStream对象实例化BinaryReader对象
BinaryReader br = new BinaryReader(fs);
//通过BinaryReader类对象的ReadBytes()方法将FileStream类对象转化为二进制数组
byte[] imgBytesIn = br.ReadBytes(Convert.ToInt32(fs.Length));
user.Photo = imgBytesIn;
从数据库中调取图片并显示
界面上需要有一个PictureBox的控件用来放图片
想通过SQL语句查到记录放到list中,然后直接取list中的图片
List<UserInfo> ulist = UFacade.SelectUserByUserID(user);
byte[] images = (byte[])ulist[0].Photo;
MemoryStream ms = new MemoryStream(images);
Bitmap bmp = new Bitmap(ms);
picPhoto.Image = bmp;