【问题标题】:Saving the Image from WPF control to SQL Server DB将图像从 WPF 控件保存到 SQL Server DB
【发布时间】:2013-11-26 02:27:41
【问题描述】:

我有一个用 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))。

请给我建议。谢谢。

【问题讨论】:

    标签: sql-server wpf wpf-controls


    【解决方案1】:

    您不能在数据库中保存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
    

    【讨论】:

    • 那么 SQL Server 2012 中怎么会有 Image 数据类型呢?还有,SQL中没有字节数组数据类型,怎么存储呢?
    • image data type in SQL server 实际上是一个字节数组。链接的文章还说:Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.
    猜你喜欢
    • 1970-01-01
    • 2016-12-27
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-15
    • 1970-01-01
    相关资源
    最近更新 更多