//选择图片事件
private void pictureBox1_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "JPG|*.jpg|BMP|*.bmp|PNG|*.png";
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(dlg.FileName);
txtFilePath = dlg.FileName;
}
}
//定义将图片转化为长二进制代码的函数getphoto()
public Byte[] getphoto(string photopath)
{
string str = photopath;
FileStream file = new FileStream(str, FileMode.Open, FileAccess.Read);
Byte[] bytBLOBData = new Byte[file.Length];
file.Read(bytBLOBData, 0, bytBLOBData.Length);
file.Close();
return bytBLOBData;
}
//然后..就是将转换成二进制码的图片插入数据库中..下面是简单的也是重要的sql语句..
if (txtFilePath != "")
{
Byte[] bytBLOBData = getphoto(txtFilePath);//将图片转成二进制
dr["Avatar"] = bytBLOBData;
//最后如何把转换二进制后的数据保存到数据库就不必多说了吧。
}
//把图片从数据库中取出然后显示在pictureBox控件
if (dr["Avatar"].ToString() == "")
{
}
else
{
byte[] image = (byte[])(dr["Avatar"]);//在数据库的字段“Avatar”中取出数据然后转换成二进制
pictureBox1.Image = Image.FromStream(new MemoryStream(image));//把二进制转化成图片
}