将WPF控件中的图像保存到SQL Server数据库。

10 浏览
0 Comments

将WPF控件中的图像保存到SQL Server数据库。

我有一个使用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();
}

在运行这段代码并点击保存到数据库按钮后,我收到了以下错误信息。

无法将对象类型System.Windows.Controls.Image映射到已知的托管提供程序

在SQL Server数据库中,我有一行(Picture(Image,null))。

请给我一些建议。谢谢。

0
0 Comments

问题的出现原因:

在WPF控件中,无法直接将Image控件保存到数据库中。相反,应该通过适当的位图编码器将图像编码到Image控件的Source属性中,并将编码后的缓冲区以字节数组的形式存储。

解决方法:

1. 将图像编码为位图对象:

byte[] buffer;
var bitmap = pictureImage.Source as BitmapSource;
var encoder = new PngBitmapEncoder(); //或者其他编码器
encoder.Frames.Add(BitmapFrame.Create(bitmap));

2. 将编码后的图像保存到字节数组中:

using (var stream = new MemoryStream())
{
    encoder.Save(stream);
    buffer = stream.ToArray();
}

3. 将字节数组存储到数据库中。

关于SQL Server 2012中的Image数据类型以及在SQL中不存在字节数组数据类型的问题:

SQL Server 2012中的Image数据类型实际上是一个字节数组。相关文章还提到:避免在新的开发工作中使用这些数据类型,并计划修改当前使用它们的应用程序。而应该使用nvarchar(max)、varchar(max)和varbinary(max)代替。

0