如何在C#中从数据库中检索时将varBinary转换为图像或video

我正在使用visual studio 2010(桌面应用程序)并使用LINQ to SQL将图像/video或音频文件保存到dataType VarBinary(MAX)中的数据库。 这个我可以做…问题是,我无法得到它们并在xaml中显示它们因为我无法使转换部分正确。 这是我到目前为止(尽管它不起作用); private void bt_Click(object sender,RoutedEventArgs e){databaseDataContext context = new databaseDataContext();

var imageValue = from s in context.Images where s.imageID == 2 select s.imageFile; value = imageValue.Single().ToString(); //convert to string and taking down to next method to get converted in image } public string value { get; set; } public object ImageSource //taking from http://stackoverflow.com/ { get { BitmapImage image = new BitmapImage(); try { image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.CreateOptions = BitmapCreateOptions.IgnoreImageCache; image.UriSource = new Uri(value, UriKind.Absolute); image.EndInit(); Grid.Children.Add(image); } catch { return DependencyProperty.UnsetValue; } return image; } } 

我甚至不确定我是否在正确的轨道上? 我假设video或音频是非常相似的方法?

由于您的图像以二进制格式存储在数据库中,因此您希望通过利用MemoryStream对象将其“流式化”为图像对象。

查看代码,您的解决方案将如下所示:

 BitmapImage bmpImage = new BitmapImage(); MemoryStream msImageStream = new MemoryStream(); msImageStream.Write(value, 0, value.Length); bmpCardImage.BeginInit(); bmpCardImage.StreamSource = new MemoryStream(msImageStream.ToArray()); bmpCardImage.EndInit(); image.Source = bmpCardImage; 

这很容易,如果您有二进制数据并想要创建一个Image对象,请使用以下代码:

 public Image BinaryToImage(byte[] binaryData) { MemoryStream ms = new MemoryStream(binaryData); Image img = Image.FromStream(ms); return img; } 

干杯,马克斯

如果你已经有字节并validation你保存的内容是否正确,你可以将字节保存到文件中打开它….

 string tempFile = Path.GetTempFileName(); MemoryStream ms = new MemoryStream(bytes); //bytes that was read from the db //Here I assume that you're reading a png image, you can put any extension you like is a file name FileStream stream = new FileStream(tempFile + ".png", FileMode.Create); ms.WriteTo(stream); ms.Close(); stream.Close(); //And here we open the file with the default program Process.Start(tempFile + ".png"); 

后来你可以使用Dillie-O的答案和流….

Dillie-O的代码提供了一个非常好的库扩展方法:

  // from http://stackoverflow.com/questions/5623264/how-to-convert-varbinary-into-image-or-video-when-retrieved-from-database-in-c: public static BitmapImage ToImage(this Binary b) { if (b == null) return null; var binary = b.ToArray(); var image = new BitmapImage(); var ms = new MemoryStream(); ms.Write(binary, 0, binary.Length); image.BeginInit(); image.StreamSource = new MemoryStream(ms.ToArray()); image.EndInit(); return image; } 

谢谢Dillie-O!