Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InteropBitmap to BitmapImage

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();
            }
        }
like image 981
Tony The Lion Avatar asked Mar 13 '10 22:03

Tony The Lion


3 Answers

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

like image 196
Thomas Levesque Avatar answered Nov 06 '22 12:11

Thomas Levesque


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;
            }
        }
    }
like image 3
caesay Avatar answered Nov 06 '22 11:11

caesay


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;
        }
    }
}
like image 1
Muhammet Emin ERDOĞAN Avatar answered Nov 06 '22 13:11

Muhammet Emin ERDOĞAN