WPF将图片存入数据库再从数据库获取显示

因为需要将图片保存至数据库,必须取得图片的Stream, 在设置Image控件的Srouce属性应该赋值为图片的Steram。

BitmapImage bitmapImage;
bitmapImage = new BitmapImage();

bitmapImage.BeginInit();

bitmapImage.StreamSource = System.IO.File.OpenRead(@"E:/2.jpg");

bitmapImage.EndInit();

image.Source = bitmapImage;//imageXAML页面上定义的Image控件

 

这样一来的话我们就能很容易的获取需要保存数据库图片的流。

 

首先定义一个字节数组,数组的长度和图片流的长度一致,然后将流中的内容读取至字节数组

byte[] imageData = new byte[bitmapImage.StreamSource.Length];

// now, you have get the image bytes array, and you can store it to SQl Server

bitmapImage.StreamSource.Seek(0, System.IO.SeekOrigin.Begin);//very important, it should be set to the start of the stream

bitmapImage.StreamSource.Read(imageData, 0, imageData.Length);

OK,一面所要做的工作就是将数据保存至数据库。

 

从数据库中读取数据然后加载到Image控件也很简单

#region read the image from a bytes array

System.IO.MemoryStream ms = new System.IO.MemoryStream(imageData);//imageData是从数据库中读取出来的字节数组

ms.Seek(0, System.IO.SeekOrigin.Begin);

 

BitmapImage newBitmapImage = new BitmapImage();

newBitmapImage.BeginInit();

newBitmapImage.StreamSource = ms;

newBitmapImage.EndInit();

image2.Source = newBitmapImage;

#endregion


转载出处:http://blog.csdn.net/leffort/article/details/5489425

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值