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