Saving the Image from WPF control to SQL Server DB

房东的猫 提交于 2020-01-06 12:42:08

问题


I have an application written in WPF 3.5 which at some point it saves the data in including an image in SQL Server, this is part of the code in saving the data (note this.pictureImage is a WPF Image control):-

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

After I run this and click on the saving to DB button I got the following error.

No mapping exists from object type System.Windows.Controls.Image to a known managed provider

In the SQL Server database I have a row with (Picture (Image, null)).

Please advise me. And thank you.


回答1:


You can't save an Image control in your database. Instead you should encode the image in the Image control's Source property by an appropriate bitmap encoder and store the encoded buffer as byte array.

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


来源:https://stackoverflow.com/questions/20199693/saving-the-image-from-wpf-control-to-sql-server-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!