2017-02-09 167 views
2

這是我在網格(WPF)中打印圖像的C#代碼,現在我想要 將此圖像存儲在數據庫中,我在數據庫中的列名稱爲 Image.I具有所有其他代碼數據庫連接等。請告訴我哪種方法最適合在數據庫中存儲圖像?如何使用C#將數據存儲在數據庫中?

private void button_Browse_Click(object sender, RoutedEventArgs e) 
    { 
     OpenFileDialog op = new OpenFileDialog(); 
     op.Title = "Select a picture"; 
     op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" + 
      "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" + 
      "Portable Network Graphic (*.png)|*.png"; 
     if (op.ShowDialog() == true) 
     { 
     imgPhoto.Source = new BitmapImage(new Uri(op.FileName));//this line print image in Grid 

     } 
    } 
+0

***什麼***數據庫?這很大程度上取決於您正在討論哪個具體的數據庫系統...... –

+0

@marc_s SQl服務器列數據類型的數據庫是映像。 – Shahbaz

+0

未來版本的SQL Server中將刪除'ntext','text'和'image'數據類型。避免在新的開發工作中使用這些數據類型,並計劃修改當前正在使用它們的應用程序。改爲使用'nvarchar(max)','varchar(max)'和'varbinary(max)'。 [詳細在這裏](http://msdn.microsoft.com/en-us/library/ms187993.aspx) –

回答

0

您可以使用VARBINARY(MAX)存儲任何類型的文件:

我給你通過自己的例子,希望它幫助。

首先創建一個表(比方說tblSampleImage)然後添加兩列(文件名VARCHAR(20)FileContent VARBINARY(MAX)

下面是用於插入和取出一個樣品CS代碼從數據庫文件:

public void insertFile() 
{ 
    string fileName= Path.GetFileName(@"your file full path"); 
    string filePath= Path.GetFullPath(@"your file full path"); 
    if (!File.Exists(filePath)) 
      { 
       MessageBox.Show("File not found"); 
       return; 
      } 
    byte[] contents= File.ReadAllBytes(filePath); 
    string insertStmt = "INSERT INTO tblSampleImage(FileName, FileContent) VALUES(@FileName, @FileContent)"; 
    SqlConnection connection = new SqlConnection(); 
    connection.ConnectionString = "connectionString"; 
    using (SqlCommand cmdInsert = new SqlCommand(insertStmt, connection)) 
      { 
      cmdInsert.Parameters.Add("@FileName", SqlDbType.VarChar, 20).Value = fileName; 
      cmdInsert.Parameters.Add("@FileContent", SqlDbType.VarBinary, int.MaxValue).Value = contents; 
      connection.Open(); 
      cmdInsert.ExecuteNonQuery(); 
      connection.Close(); 
      } 
} 

提取文件

public void fetchFile() 
     { 
     string newFilePath = Path.GetFullPath(@"your new path where you store your fetched file"); 
     string fileName="File1"; //this is the file's name which is stored in database and you want to fetch 
     byte[] fileContents; 
     string selectStmt = "SELECT FileContent FROM tblSampleImage WHERE FileName = @FileName"; 
     SqlConnection connection = new SqlConnection(); 
     connection.ConnectionString = "connectionString"; 
     using (SqlCommand cmdSelect = new SqlCommand(selectStmt, connection)) 
      { 
       cmdSelect.Parameters.Add("@Filename", SqlDbType.VarChar).Value = fileName; 
       connection.Open(); 
       fileContents = (byte[])cmdSelect.ExecuteScalar(); 
       connection.Close(); 
      } 
     File.WriteAllBytes(newFilePath, fileContents); 
     MessageBox.Show("File Saved at: " + newFilePath); 
    } 
相關問題