2012-05-04 76 views
0

我正在使用以下代碼將picturebox圖像保存到數據庫。只是我需要一些代碼來將picturebox圖像從數據庫加載到picturebox。c sharp中的picturebox圖像

DialogResult dr = openFileDialog1.ShowDialog(); 
     switch (dr) 
     { 
      case DialogResult.Cancel: 
       break; 
      case DialogResult.OK: 
       pictureBox1.Image = Image.FromFile(openFileDialog1.FileName); 
       sql = new SqlConnection(@"Data Source=PC-PC\PC;Initial Catalog=Test;Integrated Security=True"); 
       cmd = new SqlCommand(); 
       cmd.Connection = sql; 
       cmd.CommandText = ("insert [Entry] ([Image]) values (@Image)"); 
       MemoryStream stream = new MemoryStream(); 
       pictureBox1.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); 
       byte[] image = stream.ToArray(); 
       cmd.Parameters.AddWithValue("@Image", image); 
       try 
       { 
        sql.Open(); 
        cmd.ExecuteNonQuery(); 
       } 
       finally 
       { 
        sql.Close(); 
       } 
       break; 
+0

你嘗試過這麼遠嗎?你用Google搜索了嗎?看看Image.FromSteam(Stream stream)方法。 – SimpleVar

+1

possible dup http://stackoverflow.com/questions/7225610/i-want-to-load-image-from-the-database-into-a-picture-box-using-loadasync-and-a –

回答

0

這裏有兩個代碼:http://www.codeproject.com/Articles/25956/Sending-Receiving-PictureBox-Image-in-C-To-From-Mi

button2_Click用於檢索圖像:

SqlConnection connect = new SqlConnection 
        ("Server=.;database=PictureDb;integrated security=true"); 
    SqlCommand command = new SqlCommand 
         ("select fldPic from tblUsers where fldCode=1", connect); 
    //for retrieving the image field in SQL SERVER EXPRESS 
    //Database you should first bring 
    //that image in DataList or DataTable 
    //then add the content to the byte[] array. 
    //That's ALL! 
    SqlDataAdapter dp = new SqlDataAdapter(command); 
    DataSet ds = new DataSet("MyImages"); 

    byte[] MyData = new byte[0]; 

    dp.Fill(ds, "MyImages"); 
    DataRow myRow; 
    myRow = ds.Tables["MyImages"].Rows[0]; 

    MyData = (byte[])myRow["fldPic"]; 

    MemoryStream stream = new MemoryStream(MyData); 
    //With the code below, you are in fact converting the byte array of image 
    //to the real image. 
    pictureBox2.Image = Image.FromStream(stream); 
+0

如果我使用在哪裏我會告訴我不正確的語法附近關鍵字在哪裏 – aliprogrammer