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

来源:互联网 发布:我的世界联机盒子端口 编辑:程序博客网 时间:2024/05/20 12:21

因为需要将图片保存至数据库,必须取得图片的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

原创粉丝点击