从数据库加载PictureBox图像

我正在尝试将图像从数据库加载到PictureBox 。 我使用以下代码将它们加载到我的图片中。 我写了一些代码,但不知道我该怎么做才能继续。

任何帮助将不胜感激。

 private void button1_Click(object sender, EventArgs e) { sql = new SqlConnection(@"Data Source=PC-PC\PC;Initial Catalog=Test;Integrated Security=True"); cmd = new SqlCommand(); cmd.Connection = sql; cmd.CommandText = ("select Image from Entry where EntryID =@EntryID"); cmd.Parameters.AddWithValue("@EntryID", Convert.ToInt32(textBox1.Text)); } 

在button1_Click中继续这样的事情:

 // Your code first, here. var da = new SqlDataAdapter(cmd); var ds = new DataSet(); da.Fill(ds, "Images"); int count = ds.Tables["Images"].Rows.Count; if (count > 0) { var data = (Byte[])ds.Tables["Images"].Rows[count - 1]["Image"]; var stream = new MemoryStream(data); pictureBox1.Image = Image.FromStream(stream); } 

假设我们有一个名为BLOBTest的表的简单数据库:

 CREATE TABLE BLOBTest ( BLOBID INT IDENTITY NOT NULL, BLOBData IMAGE NOT NULL ) 

我们可以通过以下方式检索图像代码:

 try { SqlConnection cn = new SqlConnection(strCn); cn.Open(); //Retrieve BLOB from database into DataSet. SqlCommand cmd = new SqlCommand("SELECT BLOBID, BLOBData FROM BLOBTest ORDER BY BLOBID", cn); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds, "BLOBTest"); int c = ds.Tables["BLOBTest"].Rows.Count; if(c>0) { //BLOB is read into Byte array, then used to construct MemoryStream, //then passed to PictureBox. Byte[] byteBLOBData = new Byte[0]; byteBLOBData = (Byte[])(ds.Tables["BLOBTest"].Rows[c - 1]["BLOBData"]); MemoryStream stmBLOBData = new MemoryStream(byteBLOBData); pictureBox1.Image= Image.FromStream(stmBLOBData); } cn.Close(); } catch(Exception ex) {MessageBox.Show(ex.Message);} 

此代码将数据库中BLOBTest表中的行检索到DataSet ,将最近添加的图像复制到Byte数组中,然后复制到MemoryStream对象中,然后将MemoryStream加载到PictureBox控件的Image属性中。

完整参考指南:

http://support.microsoft.com/kb/317701

 private void btnShowImage_Click(object sender, EventArgs e) { string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.\\PIS(ACU).mdb;"; Con = new OleDbConnection(@constr); Con.Open(); Com = new OleDbCommand(); Com.Connection = Con; Com.CommandText = "SELECT Photo FROM PatientImages WHERE Patient_Id = " + val + " "; OleDbDataReader reader = Com.ExecuteReader(); if (reader.Read()) { byte[] picbyte = reader["Photo"] as byte[] ?? null; if (picbyte != null) { MemoryStream mstream = new MemoryStream(picbyte); pictureBoxForImage.Image = System.Drawing.Image.FromStream(mstream); { System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(mstream); } }