我如何使用C#将图像存储在数据库中?

时间:2017-02-09 05:34:31

标签: sql-server wpf database image-processing c#-4.0

这是我的C#代码,它在Grid(WPF)中打印图像,现在我想要 将此图像存储在数据库中,我的数据库中的列名称为 Image.I有所有其他代码数据库连接等。请告诉我哪个 方法最适合数据库中的商店图像?

 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

        }
    }

1 个答案:

答案 0 :(得分:0)

您可以使用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(); } } 存储任何类型的文件:

我自己给你一个例子,希望它有所帮助。

首先创建一个表(比如 tblSampleImage ),然后添加两列( FileName VARCHAR(20) FileContent VARBINARY(MAX))< / p>

以下是从数据库中插入和提取文件的示例CS代码:

   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);
    }

获取文件

Intent intent = new  Intent(getApplicationContext(),MapsActivity.class);
intent.putExtra("SOME_NAME_HERE", theString);
startActivity(intent);