利用OpenFileDialog 获取图片存储到数据库中

private void button1_Click(object sender, EventArgs e)
        {
            string fName;
            OpenFileDialog openFileDialog = new OpenFileDialog();//实例化
            openFileDialog.InitialDirectory = "e:\\141\\";//打开的默认路径
            openFileDialog.Filter = "图像文件 (*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG"; 
            openFileDialog.RestoreDirectory = true;
            openFileDialog.FilterIndex = 1;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                fName = openFileDialog.FileName;
                //textBox1.Text = File.ReadAllText(fName);
                FileStream fs=new FileStream (fName ,FileMode.Open );
                byte [] imgbt=new byte [fs .Length ];
                BinaryReader br = new BinaryReader(fs);
                imgbt = br.ReadBytes(Convert.ToInt32(fs.Length));
                string cnnstr = "server=.;User ID=sa;Password=admin;Database=student";

                SqlConnection conn = new SqlConnection(cnnstr);
                conn.Open();
               SqlCommand comm = new SqlCommand();
                comm.Connection = conn;
            

                string sql = "insert into a values('01',@image)";
                comm.CommandType = CommandType.Text;
                comm.CommandText = sql;
                comm.Parameters.Add("image", SqlDbType .Image   , imgbt.Length);
                comm.Parameters[0].Value = imgbt;
                comm.ExecuteNonQuery();
                conn.Close();
        }

再读取出来

            SqlDataReader dr = comm.ExecuteReader();
                      while (dr.Read())
            {
                if (dr["imagetest"] != DBNull.Value)    
                {
                    MemoryStream ms = new MemoryStream((byte[])dr["imagetest"]);//把照片读到MemoryStream里      
                    Image imageBlob = Image.FromStream(ms, true);//用流创建Image  
                    
                    pictureBox1.Image = imageBlob;//输出图片      
                }
                else//照片字段里没值,清空pb      
                {
                    pictureBox1.Image = null;
                }
            }

posted @ 2016-07-06 11:03  慢慢摸索  阅读(554)  评论(0编辑  收藏  举报