private void button1_Click(object sender, EventArgs e)//从硬盘打开图片显示在窗体里面{OpenFileDialog op = new OpenFileDialog();//造一个打开对话框DialogResult dr =op.ShowDialog();//将打开对话框显示出来if(dr==DialogResult.OK) //如果点的是"打开"{FileStream fs = new FileStream(op.FileName,FileMode.Open); // 获取你打开图片的路径 存到fs流里面去//MessageBox.Show(op.FileName);Image img = System.Drawing.Bitmap.FromStream(fs);//通过绘图函数把fs画出来pictureBox1.Image = img;//图片框的图片内容}}
//下面是打开一张图片存到数据库里面去private void button2_Click(object sender, EventArgs e) //打开一张图片存到数据库里面去 {OpenFileDialog op = new OpenFileDialog();DialogResult dr = op.ShowDialog();if (dr == DialogResult.OK){FileStream fs = new FileStream(op.FileName,FileMode.Open); //获取你打开图片的路径存到fs里面去//下面开始将路径转化为字节 存到数据库里面去BinaryReader br = new BinaryReader(fs); //把fs(存放图片路径的流)转化为二进制 存到br里面去 BinaryReader 二进制读取器//int[] x= new int[10];byte[] butter=new byte[fs.Length]; //造一个字节类型的数组butter = br.ReadBytes((int)fs.Length); //给字节butter赋值 ,赋的值是转化为二进制数据的流//下面开始连接数据库 ,然后将图片存到里面去SqlConnection conn = new SqlConnection("server=.;database=Cml;user=sa;pwd=123");SqlCommand cmd = conn.CreateCommand();conn.Open();cmd.CommandText = "insert into lk values(@s)";cmd.Parameters.Clear();cmd.Parameters.Add("@s",butter); //butter 打开图片的路径→二进制数据→字节 cmd.ExecuteNonQuery();cmd.Dispose();conn.Close();}}
private void button3_Click(object sender, EventArgs e)//从数据库里调图片显示在窗体上{SqlConnection conn = new SqlConnection("server=.;database=Cml;user=sa;pwd=123");SqlCommand cmd = conn.CreateCommand();conn.Open();cmd.CommandText = "select top 1* from lk order by ids desc"; //order by 排序 group by 分组SqlDataReader dr = cmd.ExecuteReader();dr.Read();//开始读取数据byte[] butter = (byte[])dr["img"]; //butter现在是字节,但是窗体里面的图片类型是image的 ,所以要转回去 MemoryStream 是记忆流MemoryStream ms = new MemoryStream(butter);//已经把butter转换成流了Image img = System.Drawing.Bitmap.FromStream(ms); //将流绘制成图片pictureBox1.Image = img;}