我想将图像保存为SQL数据库中的流,我在Silverlight中这样做:
OpenFileDialog fd = new OpenFileDialog();
if (fd.ShowDialog() == true)
{
Stream stream = fd.File.OpenRead();
byte[] binaryImage = new byte[stream.Length];
stream.Read(binaryImage, 0, (int)stream.Length);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(stream);
_business.PersonalPhoto = binaryImage;
}
使用WPF,此代码不起作用,fd.File不存在。 如何更正此代码以使用WPF
提前致谢。
答案 0 :(得分:1)
您可以按照以下更改代码
Microsoft.Win32.OpenFileDialog fd = new Microsoft.Win32.OpenFileDialog ();
if (fd.ShowDialog() == true)
{
Stream stream = File.OpenRead(fd.FileName);
byte[] binaryImage = new byte[stream.Length];
stream.Read(binaryImage, 0, (int)stream.Length);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(stream);
_business.PersonalPhoto = binaryImage;
}
答案 1 :(得分:1)
使用OpenFileDialog的FileName属性:
Stream stream = File.OpenRead(fd.FileName);
答案 2 :(得分:0)
最后我解决了这个问题,这里是将数据库中的图像存储为二进制文件的代码:
存储图像:
Microsoft.Win32.OpenFileDialog fd = new Microsoft.Win32.OpenFileDialog();
if (fd.ShowDialog() == true)
{
ILogo.Source = new BitmapImage(new Uri(fd.FileName));
Stream stream = File.OpenRead(fd.FileName);
binaryImage = new byte[stream.Length];
stream.Read(binaryImage, 0, (int)stream.Length);
}
_merchantInfo.Logo = binaryImage;
_context.SaveChanges();
感谢大家帮助我:)