2011-01-23 19 views
2

ValueConverter中,我試圖將System.Data.Linq.Binary(SQL CE映像)轉換爲BitmapImage。此方法效果(圖像顯示正確的形式):爲什麼這兩種從SQL CE加載圖像到WPF圖像的方法產生不同的結果?

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

這種方法確實NOT工作(但沒有拋出異常,奇怪的):

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

良好的編程習慣指出您應該處理你創建的任何流...所以我很困惑爲什麼第二種方法不起作用,但第一種方法。任何見解?

+0

我有一些簡單的示例代碼瀏覽:http://erikej.blogspot.com/2009/11/how-to-save-and-retrieve-images-using.html – ErikEJ 2011-01-23 10:00:48

+0

從字節轉化代碼[]以圖片使用`Image.FromStream(ms);`這似乎是Windows窗體特定的(我正在使用WPF)。我檢查了`System.Windows.Media.Imaging.BitmapImage`和`System.Windows.Controls.Image`,他們都沒有`FromStream`方法。感謝您的鏈接。 – Pwninstein 2011-01-23 15:27:01

回答

2

試試這個:

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塊是指流被關閉之前的圖像實際上是解碼。

+0

我會試試這個,謝謝! – Pwninstein 2011-01-23 03:58:44

0

我的猜測是,當你處置MemoryStream時,你將取消位圖的StreamSource。所以,當位圖嘗試渲染時,沒有有效的數據可用。

相關問題