InteropBitmap 转 BitmapImage

5
我正在尝试将一个Bitmap(SystemIcons.Question)转换为BitmapImage,以便在WPF Image控件中使用它。
我有以下方法将其转换为BitmapSource,但它返回一个InteropBitmapImage,现在的问题是如何将它转换为BitmapImage。直接强制转换似乎不起作用。
有人知道怎么做吗?
代码:
 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? - Thomas Levesque
@Thomas,没错!我解决了它,而且不需要进行转换! :) 把你的评论作为答案,我会接受它! - Tony The Lion
3个回答

9

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


3

您应该能够使用:

    public 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;
                System.Windows.Media.Imaging.BitmapImage bImg = new System.Windows.Media.Imaging.BitmapImage();
                bImg.BeginInit();
                bImg.StreamSource = new MemoryStream(ms.ToArray());
                bImg.EndInit();
                return bImg;
            }
        }
    }

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接