为什么这两种将图像从 SQL CE 加载到 WPF 图像的方法会产生不同的结果?
在 ValueConverter 中,我尝试将 System.Data.Linq.Binary(SQL CE 图像)转换为 BitmapImage。此方法有效(图像在表单上正确显示):
public object Convert(object value, Type targetType, object parameter,
CultureInfo culture) {
Binary binary = value as Binary;
if (binary != null) {
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = new MemoryStream(binary.ToArray());
bitmap.EndInit();
return bitmap;
}
return null;
}
此方法不有效(但奇怪的是没有抛出异常):
public object Convert(object value, Type targetType, object parameter,
CultureInfo culture) {
Binary binary = value as Binary;
if (binary != null) {
using (var stream = new MemoryStream(binary.ToArray())) {
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = stream;
bitmap.EndInit();
return bitmap;
}
}
return null;
}
良好的编程实践表明您应该处理您创建的任何流。所以我很困惑为什么第二种方法不起作用,但第一种方法可以。有什么见解吗?
In a ValueConverter
, I was trying to convert a System.Data.Linq.Binary
(SQL CE image) to a BitmapImage
. This method works (image is show correctly on the form):
public object Convert(object value, Type targetType, object parameter,
CultureInfo culture) {
Binary binary = value as Binary;
if (binary != null) {
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = new MemoryStream(binary.ToArray());
bitmap.EndInit();
return bitmap;
}
return null;
}
This method does NOT work (but no exception is thrown, strangely):
public object Convert(object value, Type targetType, object parameter,
CultureInfo culture) {
Binary binary = value as Binary;
if (binary != null) {
using (var stream = new MemoryStream(binary.ToArray())) {
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = stream;
bitmap.EndInit();
return bitmap;
}
}
return null;
}
Good programming practice states that you should dispose of any streams you create... so I'm confused why the second method doesn't work, but the first does. Any insights?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请尝试这样做:
在您的非工作版本中,您的
using
块意味着在图像实际解码之前关闭流。Try this instead:
In your non-working version, your
using
block means the stream is closed before the image is actually decoded.我的猜测是,当您处置
MemoryStream
时,您正在使位图的StreamSource
无效。因此,当位图尝试渲染时,没有可用的有效数据。My guess would that when you are disposing the
MemoryStream
, you are nullifying theStreamSource
of the bitmap. So, when the bitmap tries to render, there is no valid data available.