wpf 展示sql server 中iamge类型数据
image数据是二进制数据,现有一个字段存储的是图片,我需要用wpf的image控件把图片展示出来
使用的是三层技术,首先定义模型层,image类型的数据在模型层中用byte[]表示
public class A { public int Id { get; set; } public byte[] aa { get; set; } }
之后定义数据访问层代码:,DBHelper就不展示了
public class ADAL { public List<A> GetList(string where) { List<A> list = new List<A>(); SqlDataReader reader = DBHelper.ExecuteReader("select * from a where 1=1 and " + where); while (reader.Read()) { list.Add(new A() { Id = Convert.ToInt32(reader["id"]), Sxqm = reader["aa"].ToString() == "" ? null : (byte[])reader["aa"] }); } return list; } }
定义完数据访问层后定义业务逻辑层代码:
public class AManager { private readonly ADAL dal = new ADAL(); public A Get(string id,ref string e) { string where = $"id = '{id}'"; try { return dal.GetList(where)[0]; } catch (Exception exception) { e = exception.Message; } return null; } }
最后写ui,xaml中写:
<Image x:Name="Image"></Image>
后台代码:
AManager manager = new AManager(); string message = ""; A a = manager.Get("1", ref message); this.DataContext = a; if (a.aa != null) { // 将byte[] 转换为 BitmapImage MemoryStream stream = new MemoryStream(a.aa); var image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.StreamSource = stream; image.EndInit(); image.Freeze(); // 给Image绑定图片 this.Image.Source = image; } if (message != "") { MessageBox.Show(message); }