数据库存取图片

   private void button1_Click(object sender, EventArgs e) //窗体打开文件图片
        {
            openFileDialog1.Filter = "@.jpg|*.jpg|all files|*.*";
            DialogResult dr = openFileDialog1.ShowDialog();
            if (dr == DialogResult.OK)
            {
                FileStream fs = new FileStream(openFileDialog1.FileName,FileMode.Open,FileAccess.Read);
                Image img = System.Drawing.Bitmap.FromStream(fs);
                pictureBox1.Image = img;

            }
        }
       
        private void button2_Click(object sender, EventArgs e)  //图片存入数据库
        {
            openFileDialog1.Filter = "@.jpg|*.jpg|@.gif|*.gif|All files|*.*";
            DialogResult dr = openFileDialog1.ShowDialog();
            if (dr == DialogResult.OK)
            {
                FileStream fs = new FileStream(openFileDialog1.FileName,FileMode.Open,FileAccess.Read);
                BinaryReader br = new BinaryReader(fs);
                byte[] buffer = br.ReadBytes(int.Parse(fs.Length.ToString()));
                SqlConnection conn = new SqlConnection("server=.;database=HQ0325;user=sa;pwd=123");
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = "insert into imgtable values(@buffer)";
                cmd.Parameters.Add("@buffer",buffer);
                conn.Open();
                cmd.ExecuteNonQuery();
                cmd.Dispose();
                conn.Close();
                MessageBox.Show("保存成功");
            }
        }

        private void button3_Click(object sender, EventArgs e)  //从数据库里获取图片并且在窗体里显示第一张
        {
            SqlConnection conn = new SqlConnection("server=.;database=HQ0325;user=sa;pwd=123");
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = "select * from imgtable where code=1";
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            dr.Read();
            
                byte[] buffer = (byte[])dr["imgs"];
         
            cmd.Dispose();
            conn.Close();
            MemoryStream ms = new MemoryStream(buffer);
            ms.Write(buffer, 0, buffer.Length);
            Image img = Image.FromStream(ms);
            pictureBox1.Image = img;
        }
    }

 

posted @ 2015-07-19 22:21  SaYes  阅读(222)  评论(0编辑  收藏  举报