问题
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