C# 从 Properties.Resources 将 BitMap 转换为 BitmapImage

C# Convert BitMap into BitmapImage from Properties.Resources

我目前正在尝试将项目资源中的 .jpeg 图像转换为 BitmapImage,以便将其显示在我的应用程序的图像字段中。

我进行了一些挖掘并发现了以下 Whosebug thread 但不幸的是,该代码仅在使用时抛出 InvalidCastException。 (“无法将 System.Windows.Interop.InteropBitmap 转换为 System.Windows.Media.Imaging.BitmapImage”)。

还有其他方法可以将 BitMap 对象转换为 BitmapImage 吗?

我现在找到了一种将 Bitmap 转换为 bitmapSource / bitmapimage 的方法。它与我在 OP 中链接的 Whosebug 线程的版本略有不同:

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

这个returns一个BitmapSource对象,可以用来在WPF图像元素中显示一个Image