DB byte[] 转为bitmapImage,bitmapImage转为byte[] to db

将图片存入数据库中,和一般的做法一样,将图片文件保存成字节流。在SQL2005以上的版本有Image类型可以用来保存字节数组变量。

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

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

原文地址:https://www.cnblogs.com/iwangjun/p/2412753.html