这是我的 C# 代码,它在 Grid(WPF) 中打印图像,现在我想 将此图像存储在数据库中,数据库中的列名称为 图片。我有所有其他代码数据库连接等。请告诉我哪个 哪种方法最适合在数据库中存储图像?
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
}
}
最佳答案
您可以使用VARBINARY(MAX)
来存储任何类型的文件:
我自己给你举个例子,希望对你有帮助。
首先创建一个表(比如tblSampleImage)然后添加两列(FileName 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);
}
关于sql-server - 我如何使用 C# 将图像存储在数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42128993/