首先在xaml文件里定義一個Image控件,取名為img
MemoryStream stream = new MemoryStream(獲得的數據庫對象);
BitMapImage bmp = new BitMapImage();
bmp.BeginInit();//初始化
bmp.StreamSource = stream;//設置源
bmp.EndInit();//初始化結束
img.Source = bmp;//設置圖像Source
很多人用這個方法都沒有初始化BitMapImage ,這樣將會導致錯誤,並無法正常獲取圖片數據。
public class emp
{
public byte[] Photo{set;get;}
}
xaml中的代碼
private void btnChoosePhoto_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();//打開選擇文件窗口
ofd.Filter = "jpg|*.jpg|png|*.png";//過濾器
if (ofd.ShowDialog() == true)
{
string fileName = ofd.FileName;//獲得文件的完整路徑
emp.Photo = File.ReadAllBytes(fileName);//把圖像的二進制數據存儲到emp的Photo屬性中
img.Source = new BitmapImage(new Uri(fileName));//將圖片顯示到Image控件上
}
}