2013-10-14 181 views
2

我在類型文件的輸入顯示圖像,然後我想保存此圖像數據庫。我知道如何存儲varbinary或圖像到數據庫,但我不知道如何訪問輸入文件?在數據庫中存儲圖像

SqlConnection con = new SqlConnection(stcon); 
     SqlCommand command = new SqlCommand(); 


      string path = ""; 
      System.Drawing.Image img = System.Drawing.Image.FromFile(path); 
      MemoryStream tmpStream = new MemoryStream(); 
      img.Save(tmpStream, ImageFormat.Png); // change to other format 
      tmpStream.Seek(0, SeekOrigin.Begin); 
      byte[] imgBytes = new byte[100000]; 
      tmpStream.Read(imgBytes, 0, 100000); 

      command.CommandText = "INSERT INTO image(image) VALUES (:image)"; 
      IDataParameter par = command.CreateParameter(); 
      par.ParameterName = "image"; 
      par.DbType = DbType.Binary; 
      par.Value = imgBytes; 
      command.Parameters.Add(par); 
      command.ExecuteNonQuery(); 
+0

你是什麼確切的問題?? U不能存儲你想從數據庫中回收圖像的圖像? –

+0

你的問題是什麼?你想從sql或其他檢索圖像? – Regon

+1

'你','U'?關於該註釋的語法錯誤:-) – Garry

回答

1

您可以簡單地使用System.IO.File.ReadAllBytes方法來讀取二進制文件:

byte[] imgBytes = System.IO.File.ReadAllBytes(@"c:\temp\capture.png"); 

所以你的情況,你可以使用它像(更換路徑):

string path = @"c:\temp\capture.png"; 
byte[] imgBytes = System.IO.File.ReadAllBytes(path); 

command.CommandText = "INSERT INTO image(image) VALUES (:image)"; 
IDataParameter par = command.CreateParameter(); 
par.ParameterName = "image"; 
par.DbType = DbType.Binary; 
par.Value = imgBytes; 
command.Parameters.Add(par); 
command.ExecuteNonQuery(); 
0

隨着你的問題,我認爲你已經插入圖像到表中,現在想要檢索插入的圖像。如果是的話,你可以試試,

   string sql = ""; 
       string address = ""; 
       SqlConnection con = new SqlConnection(ConnectionString); 
       sql = "SELECT Image from ImageTable where imageId=1"; 

       DataSet ds = new DataSet(); 
       SqlCommand cmd = new SqlCommand(sql, con); 
       SqlDataAdapter adp = new SqlDataAdapter(); 
       adp.SelectCommand = cmd; 
       adp.Fill(ds,"Data"); 


       address = "C:\\Users\\CARDIT\\Desktop\\Imag1.jpeg"; 
       byte[] bytes = (byte[])ds.Tables["Data"].Rows[i][0]; 
       MemoryStream ms = new MemoryStream(bytes); 


       System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms); 

        Bitmap bmSave = new Bitmap(returnImage); 
        Bitmap bmTemp = new Bitmap(bmSave); 

        Graphics grSave = Graphics.FromImage(bmTemp); 
        grSave.DrawImage(returnImage, 0, 0, returnImage.Width, returnImage.Height); 

        bmTemp.Save(address); //If You want to save in Specific location 

        pictureBox1.Image = bmSave; //if you want to use Image in Picturebox Control;