-1

I'm currently trying to convert a .jpeg image from the Project resources into a BitmapImage to be abe to display it on to the Image field of my appliaction.

I have done some digging and found the following StackOverflow thread but unfortunately that code only throws a InvalidCastException when used. ("Can't convert System.Windows.Interop.InteropBitmap to System.Windows.Media.Imaging.BitmapImage").

Is there another way to convert a BitMap object into BitmapImage ?

GoldNova
  • 147
  • 1
  • 1
  • 11

1 Answers1

1

I have now found a way to convert the Bitmap to bitmapSource / bitmapimage. It's a slightly different version than the versions of the Stackoverflow thread I linked in the OP:

private static BitmapSource Bitmap2BitmapImage(Bitmap bitmap)
{
    IntPtr hBitmap = bitmap.GetHbitmap();
    BitmapSource retval = null;

    try
    {
        retval = Imaging.CreateBitmapSourceFromHBitmap(
                 hBitmap,
                 IntPtr.Zero,
                 Int32Rect.Empty,
                 BitmapSizeOptions.FromEmptyOptions());
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

    return retval;
}

This returns a BitmapSource Object, which can be used to display an Image in the WPF image Element

GoldNova
  • 147
  • 1
  • 1
  • 11