2011-09-21 16 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。 –

相关问题