【问题标题】:Why do these two methods of loading images from SQL CE into a WPF Image produce different results?为什么这两种将图像从 SQL CE 加载到 WPF 图像中的方法会产生不同的结果?
【发布时间】:2011-01-23 03:14:59
【问题描述】:

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;
}

良好的编程实践表明您应该处理您创建的任何流......所以我很困惑为什么第二种方法不起作用,但第一种方法起作用。有什么见解吗?

【问题讨论】:

  • 我这里有一些更简单的示例代码:erikej.blogspot.com/2009/11/…
  • 您从 byte[] 到 Image 的转换代码使用 Image.FromStream(ms);,这似乎是特定于 Windows 窗体的(我使用的是 WPF)。我检查了System.Windows.Media.Imaging.BitmapImageSystem.Windows.Controls.Image,它们都没有FromStream 方法。不过感谢您的链接。

标签: wpf sql-server-ce memorystream valueconverter


【解决方案1】:

试试这个:

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.CacheOption = BitmapCacheOption.OnLoad; 
            bitmap.StreamSource = stream;
            bitmap.EndInit();
            bitmap.Freeze(); 
            return bitmap;
        }
    }
    return null;
}

在您的非工作版本中,您的 using 块意味着流在图像实际解码之前关闭

【讨论】:

    【解决方案2】:

    我的猜测是,当您处理MemoryStream 时,您将取消位图的StreamSource。因此,当位图尝试渲染时,没有可用的有效数据。

    【讨论】:

    • 但他在处理MemoryStream 之前返回位图,不是吗?
    • @VoodooChild,好点子,但 WPF 是否有可能在调用 Dispose() 之后才尝试实际渲染位图?
    猜你喜欢
    • 1970-01-01
    • 2019-07-20
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    相关资源
    最近更新 更多