我有一个用WPF 3.5编写的应用程序,它在某个时刻将数据保存在SQL Server中,包括图像,这是保存数据的代码的一部分(注意this.pictureImage
是WPF Image
控件):-
using (SqlCommand command = myConnection.CreateCommand())
{
String sqlInsertCommand = "INSERT INTO Info_Id (idNumber, FirstName, Nationality, Image) VALUES (@idNumber, @firstName, @nationality, @image)";
command.CommandText = sqlInsertCommand;
command.CommandType = System.Data.CommandType.Text;
command.Parameters.AddWithValue("@idNumber", this.cardIdTextBlock.Text);
command.Parameters.AddWithValue("@firstName", this.fullNameTextBlock.Text);
command.Parameters.AddWithValue("@nationality", this.nationaltyTextBlock.Text);
command.Parameters.AddWithValue("@image", this.pictureImage);
command.ExecuteNonQuery();
}
在我运行这个并点击保存到DB按钮后,我得到了以下错误。
不存在从对象类型System.Windows.Controls.Image到已知托管提供程序的映射
在SQL Server数据库中,我有一行(Picture(Image,null))。
请给我建议。谢谢。
您无法在数据库中保存Image
控件。相反,您应该使用适当的位图编码器对image控件的Source
属性中的图像进行编码,并将编码的缓冲区存储为字节数组。
byte[] buffer;
var bitmap = pictureImage.Source as BitmapSource;
var encoder = new PngBitmapEncoder(); // or one of the other encoders
encoder.Frames.Add(BitmapFrame.Create(bitmap));
using (var stream = new MemoryStream())
{
encoder.Save(stream);
buffer = stream.ToArray();
}
// now store buffer in your DB