2011-09-21 60 views
1

這是我你如何獲得一個位圖圖像到一個WPF的ListView

<GridViewColumn Header="Status" > 
    <GridViewColumn.CellTemplate> 
     <DataTemplate> 
      <StackPanel Orientation="Horizontal"> 
       <Image Source="{Binding Image}" Width="22" Height="22"/> 
      </StackPanel> 
     </DataTemplate> 
    </GridViewColumn.CellTemplate> 
</GridViewColumn> 

圖片是我從Namespace.Resources得到一個System.Drawing.Bitmap圖像。

無論我嘗試什麼,我都無法在列中顯示任何圖像。

回答

3

您需要將System.Drawing.Bitmap轉換爲ImageSource,這是WPF用於圖像的內容。您可以通過Imaging.CreateBitmapSourceFromHBitmap執行此操作:

// Include, in your class or elsewhere: 
[System.Runtime.InteropServices.DllImport("gdi32.dll")] 
private static extern bool DeleteObject(IntPtr hObject); 

Bitmap image = LoadYourBitmap(); 

IntPtr hbitmap = image.GetHbitmap(); 
try 
{ 
    var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
     hbitmap, IntPtr.Zero, Int32Rect.Empty, 
     Imaging.BitmapSizeOptions.FromEmptyOptions()); 
} 
finally 
{ 
    // Clean up the bitmap data 
    DeleteObject(hbitmap); 
} 
+0

非常感謝! – Fatal510

+0

所以我對此感興趣,因爲我一直在使用另一種方法將'Bitmap'轉換爲'BitmapSource',從MemoryStream初始化它(我將圖像數據作爲Base64編碼的字符串獲取,因此它是有意義的) 。運行一些測試後,這種方法比我的速度快得多(使用100個樣本的速度一直快70%),但隨着我稱這種方法,內存使用量不斷增加。我的方法不會發生這種情況,因爲我花了一些時間確保儘快清除所有內容(最初我們有一些內存問題)。任何想法爲什麼這是? –

+0

我也會關注它,所以非常感謝。對我來說一眼就沒有多大意義,但是在將320x240圖像轉換100次後,我發現在我的工作集中跳到了〜30MB。 –

相關問題