問題描述
我有一個用 WPF 3.5 編寫的應用程序,它在某些時候將數據保存在 SQL Server 中包含圖像中,這是保存數據的代碼的一部分(注意 this.pictureImage
是一個 WPF Image
控件):-
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.
不存在從對象類型 System.Windows.Controls.Image 到已知托管提供程序的映射
No mapping exists from object type System.Windows.Controls.Image to a known managed provider
在 SQL Server 數據庫中,我有一行 (Picture (Image, null)).
In the SQL Server database I have a row with (Picture (Image, null)).
請多多指教.謝謝.
推薦答案
您無法在數據庫中保存 Image
控件.相反,您應該通過適當的位圖編碼器在 Image 控件的 Source
屬性中對圖像進行編碼,并將編碼的緩沖區存儲為字節數組.
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
這篇關于將圖像從 WPF 控件保存到 SQL Server DB的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!