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;//image是XAML页面上定义的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);

或者采用下面另一种方法来做:

// Read a resource stream from whichever resource file
  Image image = (Image)ue;
  System.Windows.Resources.StreamResourceInfo sri = App.GetResourceStream(new Uri(image.Source.ToString()));
  // Read the resource stream into a byte array.
   byte[] imageData= new byte[sri.Stream.Length];
     int numBytesToRead = (int)sri.Stream.Length;
     int numBytesRead = 0;
    while (numBytesToRead > 0)
       {
           int n = sri.Stream.Read(imageData, numBytesRead, numBytesToRead);

             if (n == 0)
                    break;

              numBytesRead += n;
                numBytesToRead -= n;
         }
         numBytesToRead = 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

 

附:数组和字符串之间的转换可以采用以下方式。

//ENCODE

String imgString= Convert.ToBase64String(imageData);                   
  //DECODE
 byte[] imageData= Convert.FromBase64String(imgString);


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值