InteropBitmap to BitmapImage
Asked Answered
B

3

5

I'm trying to Convert a Bitmap (SystemIcons.Question) to a BitmapImage so I can use it in a WPF Image control.

I have the following method to convert it to a BitmapSource, but it returns an InteropBitmapImage, now the problem is how to convert it to a BitmapImage. A direct cast does not seem to work.

Does anybody know how to do it?

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

property to return BitmapImage: (Bound to my Image Control)

public BitmapImage QuestionIcon
        {
            get
            {
                return  (BitmapImage)ConvertToBitmapSource();
            }
        }
Bumper answered 13/3, 2010 at 22:21 Comment(2)
InteropBitmapImage inherits from ImageSource, so you can use it in an Image control. Why do you need it to be a BitmapImage ?Hackamore
@Thomas, correct! I solved it without needing to do the conversion! :) Put your comment as an answer and I'll accept it!Bumper
H
9

InteropBitmapImage inherits from ImageSource, so you can use it directly in an Image control. You don't need it to be a BitmapImage.

Hackamore answered 14/3, 2010 at 13:0 Comment(0)
P
3

You should be able to use:

    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;
            }
        }
    }
Pulchritude answered 13/3, 2010 at 23:6 Comment(0)
H
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;
        }
    }
}
Homosporous answered 7/4, 2017 at 8:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.