InteropBitmap到BitmapImage

时间:2010-03-13 22:21:45

标签: c# wpf bitmapimage bitmapsource interopbitmapimage

我正在尝试将Bitmap (SystemIcons.Question)转换为BitmapImage,以便我可以在WPF图像控件中使用它。

我有以下方法将其转换为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();
            }
        }

3 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:1)

你应该可以使用:

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

答案 2 :(得分: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;
        }
    }
}