该程序采用窗体设计的形式编程
需要用到的控件:button、picturebox、textbox
声明一个存储照片的路径的全局变量
string strImage = "";//声明文件路径的变量
做一个在文件夹选择图片的按钮,并用picturebox展示图片
private void button3_Click(object sender, EventArgs e)
{
//创建OpenFileDialog对象
OpenFileDialog openFileDialog = new OpenFileDialog();
//创建一个筛选器
openFileDialog.Filter = "jpeg文件|*.jpg";
//设置对话框标题
openFileDialog.Title = "打开图片`:";
//启用帮助按钮
openFileDialog.ShowHelp = true;
//如果结果为打开,则选定文件
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
strImage = openFileDialog.FileName;
Bitmap curBitmap = (Bitmap)Image.FromFile(strImage);
pictureBox1.Image = curBitmap;
Invalidate();
}
}
连接数据库,用文件流的方式把图片存到数据库中
private void button4_Click(object sender, EventArgs e)
{
//设置连接路径
string sqlstr = "Data Source = DESKTOP-OLSHFKE; Initial Catalog = MyData; User ID = wuyongzhao ; Password = 123";
//创建数据库连接对象
SqlConnection sqlCon = new SqlConnection(sqlstr);
//创建文件流对象
FileStream fs = new FileStream(strImage, FileMode.Open, FileAccess.Read);
//创建二进制流对象
BinaryReader BReader = new BinaryReader(fs);
//得到字节数组
byte[] byteImage = BReader.ReadBytes((int)fs.Length);
//创建命令对象
SqlCommand sqlCmd = new SqlCommand("Insert into tb_Image(name,photo)values(@name,@photo)", sqlCon);
//添加参数并赋值
sqlCmd.Parameters.Add("@name", SqlDbType.VarChar, 50).Value = textBox2.Text;
//添加参数并赋值
sqlCmd.Parameters.Add("@photo", SqlDbType.Image).Value = byteImage;
//打开数据库连接
sqlCon.Open();
//执行SQL语句
sqlCmd.ExecuteNonQuery();
//关闭数据库连接
sqlCon.Close();
//保存成功
MessageBox.Show("保存成功");
}