OpenFileDialog openfiledialog1 = new OpenFileDialog(); if (openfiledialog1.ShowDialog() == DialogResult.OK) { textBox1.Text = openfiledialog1.FileName; // 文件路徑 } string imageName = DateTime.Now.ToString( " yyyymmddhhMMss " ); // 生成文件名到數據庫 FileStream fs = new FileStream(textBox1.Text, FileMode.Open); BinaryReader br = new BinaryReader(fs); Byte[] byData = br.ReadBytes(( int )fs.Length); // 生成二進制流 fs.Close(); // 將圖片轉化為二進制流,存入數據庫 string conn = " server=.;database=ImageDB;Uid=sa;Pwd=1234 " ; SqlConnection myconn = new SqlConnection(conn); myconn.Open(); string str = " insert into ImageFile (ImageName,ImageContext) values(@name,@file) " ; SqlCommand mycomm = new SqlCommand(str, myconn); mycomm.Parameters.Add( " @file " , SqlDbType.Binary, byData.Length); mycomm.Parameters[ " @file " ].Value = byData; mycomm.Parameters.Add( " @name " , SqlDbType.NVarChar, 50 ); mycomm.Parameters[ " @name " ].Value = imageName; mycomm.ExecuteNonQuery(); // 將二進制流寫入數據庫,對應數據庫IMAGE類型 myconn.Close(); // 將二進制流轉化為IMAGE str = " select top 1 ImageContext from ImageFile where ImageName=' " + imageName + " ' " ; myconn = new SqlConnection(conn); SqlDataAdapter sda = new SqlDataAdapter(str, conn); DataSet myds = new DataSet(); myconn.Open(); sda.Fill(myds); myconn.Close(); Byte[] Files = (Byte[])myds.Tables[ 0 ].Rows[ 0 ][ " ImageContext " ]; MemoryStream ms = new MemoryStream(Files); Image i = Image.FromStream(ms); pictureBox1.Image = i; // 綁定到pictureBox1控件上
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
