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

发布于 2025-01-16 16:45:37 字数 331 浏览 5 评论 0原文

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

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

还有另一种方法可以将 BitMap 对象转换为 BitmapImage 吗?

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 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

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

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

它返回一个 BitmapSource 对象,可用于在 WPF 图像元素中显示图像

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文