5

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

我有以下方法将其转换为 a BitmapSource,但它返回一个InteropBitmapImage,现在的问题是如何将其转换为 a 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();
            }
        }
4

3 回答 3

9

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

于 2010-03-14T13:00:33.383 回答
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;
            }
        }
    }
于 2010-03-13T23:06:32.330 回答
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;
        }
    }
}
于 2017-04-07T08:20:42.387 回答