我想要转换一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();
            }
        }
有帮助吗?

解决方案

InteropBitmapImageImageSource继承,所以可以直接在Image控制使用它。你不需要它是一个BitmapImage

其他提示

您应该能够使用:

    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;
            }
        }
    }
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;
        }
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top