2011-05-11 118 views
1

我無法將圖片插入到數據庫中。這是我的示例代碼。我可以從我的計算機中選擇圖像並顯示在圖片框中。一旦我嘗試存儲顯示的圖像在圖片框中向數據庫表示對象引用未設置爲對象的實例。c#將圖片存儲到數據庫

這是我的示例代碼。

  namespace picutre_storage 
    { 
     public partial class Form1 : Form 
     { 
     public Form1() 
     { 
     InitializeComponent(); 
     } 

    private void button2_Click(object sender, EventArgs e) 
    { 
     try 
     { 

      SqlConnection con = new SqlConnection 
          (@"User ID=sa;Password=password123;Initial Catalog=picuture;Persist Security Info=True;Data Source=ENMEDIA-EA6278E\ENMEDIA"); 
      //I have used a table named "tblUsers" and fill the fields 
      SqlCommand cmd = new SqlCommand("INSERT INTO BLOBTest (BLOBData) VALUES (@BLOBData)", con); 

      //Save image from PictureBox into MemoryStream object. 
      MemoryStream ms = new MemoryStream(); 
      pictureBox1.Image.Save(ms,ImageFormat.Bmp); 

      //Read from MemoryStream into Byte array. 
      Byte[] bytBLOBData = new Byte[ms.Length]; 
      ms.Position = 0; 
      ms.Read(bytBLOBData, 0, Convert.ToInt32(ms.Length)); 

      //Create parameter for insert statement that contains image. 
      SqlParameter prm = new SqlParameter("@BLOBData", SqlDbType.VarBinary,   bytBLOBData.Length, ParameterDirection.Input, false, 
          0, 0, null, DataRowVersion.Current, bytBLOBData); 
      cmd.Parameters.Add(prm); 
      con.Open(); 
      cmd.ExecuteNonQuery(); 
      con.Close(); 
     } 
     catch (Exception ex) 
     { MessageBox.Show(""+ex); } 
    } 

     private void button3_Click(object sender, EventArgs e) 
     { 
     try 
     { 
      //Getting The Image From The System 
      OpenFileDialog open = new OpenFileDialog(); 
      open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp"; 
      if (open.ShowDialog() == DialogResult.OK) 
      { 
       pictureBox2.Image = new Bitmap(open.FileName); 
      } 
     } 
     catch (Exception) 
     { 
      throw new ApplicationException("Failed loading image"); 
     } 
    } 

2.有提前

+0

對於點2:我在救我的數據庫,我節約了圖像長度的列。 – Marco 2011-05-11 08:08:17

+2

總是將你的SqlConnection對象封裝在一個using語句中,否則你將有一個連接池泄漏!:)使用(var cnn = new SqlConnection(...)){....}(在上面的代碼中 - 一旦發生錯誤,您將遇到問題 - 您的連接不會被關閉) – Nathan 2011-05-11 08:09:44

+1

您可以使用ms.ToArray()獲取字節數組。無需進行手動分配。 – 2011-05-11 08:11:07

回答

1

在畫面box.Thank顯示它在東西我看你保存文件爲BMP格式,最初那張照片之前就存在任何方式檢查圖像的大小讓我們說jpeg或tiff格式,所以記錄被正確插入,但圖片引用了一種類型的bmp格式,並且它不存在。 我認爲你可以這樣做。

  1. ,當你得到你想要的任何 格式的圖片,然後在不同的文件夾* (如我的圖片\縮略圖)創建 縮略圖這張照片存儲。 *
  2. 獲取 圖片的擴展名,在 創建縮略圖期間將其替換爲jpg。
  3. 將其存儲在數據庫中。
  4. 檢索 圖片框中的縮略圖。你要。

如果你想知道如何創建縮略圖(將文件保存爲JPG格式,那麼最歡迎