2010-03-13 77 views
4

我想將Bitmap (SystemIcons.Question)轉換爲BitmapImage,所以我可以在WPF圖像控件中使用它。InteropBitmap到BitmapImage

我有以下方法將它轉換爲BitmapSource,但它返回InteropBitmapImage,現在的問題是如何將其轉換爲BitmapImage。直接投射似乎不起作用。

有人知道該怎麼做嗎?

CODE:

public BitmapSource ConvertToBitmapSource() 
     { 
      int width = SystemIcons.Question.Width; 
      int height = SystemIcons.Question.Height; 
      object a = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(SystemIcons.Question.ToBitmap().GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(width, height)); 

      return (BitmapSource)a; 
     } 

屬性返回的BitmapImage:(綁定到我的圖像控制)

public BitmapImage QuestionIcon 
     { 
      get 
      { 
       return (BitmapImage)ConvertToBitmapSource(); 
      } 
     } 
+2

InteropBitmapImage繼承自ImageSource,因此您可以在Image控件中使用它。爲什麼你需要它是一個BitmapImage? – 2010-03-14 02:32:00

+0

@Thomas,對!我解決了它,無需做轉換! :)把你的評論作爲答案,我會接受它! – 2010-03-14 09:49:24

回答

7

InteropBitmapImage繼承ImageSource ,因此您可以直接在Image控件中使用它。你不需要它是一個BitmapImage

+0

+1我錯過了 – caesay 2010-03-14 16:18:56

1

您應該能夠使用:

​​
0
public System.Windows.Media.Imaging.BitmapImage QuestionIcon 
{ 
    get 
    { 
     using (MemoryStream ms = new MemoryStream()) 
     { 
      System.Drawing.Bitmap dImg = SystemIcons.ToBitmap(); 
      dImg.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); 
      ms.Position = 0; 
      var bImg = new System.Windows.Media.Imaging.BitmapImage(); 
      bImg.BeginInit(); 
      bImg.StreamSource = ms; 
      bImg.EndInit(); 
      return bImg; 
     } 
    } 
}