WPF - converting Bitmap to ImageSource(WPF - 将位图转换为 ImageSource)
问题描述
我需要将 System.Drawing.Bitmap 转换为 System.Windows.Media.ImageSource 类,以便将其绑定到 WizardPage 的 HeaderImage 控件(扩展WPF 工具包).位图被设置为我编写的程序集的资源.它被这样引用:
I need to convert a System.Drawing.Bitmap into System.Windows.Media.ImageSource class in order to bind it into a HeaderImage control of a WizardPage (Extended WPF toolkit).
The bitmap is set as a resource of the assembly I write.
It is being referenced like that:
public Bitmap GetBitmap
{
get
{
Bitmap bitmap = new Bitmap(Resources.my_banner);
return bitmap;
}
}
public ImageSource HeaderBitmap
{
get
{
ImageSourceConverter c = new ImageSourceConverter();
return (ImageSource)c.ConvertFrom(GetBitmap);
}
}
转换器是我在此处找到的.我在
return (ImageSource) c.ConvertFrom(Resources.my_banner);
如何初始化 ImageSource 以避免此异常?或者还有其他方法吗?我想在之后使用它:
How can I initialize ImageSource in order to avoid this exception? Or is there another way? I want to use it afterwards like:
<xctk:WizardPage x:Name="StartPage" Height="500" Width="700"
HeaderImage="{Binding HeaderBitmap}"
Enter="StartPage_OnEnter"
提前感谢您的回答.
推荐答案
对于其他人,这有效:
//If you get 'dllimport unknown'-, then add 'using System.Runtime.InteropServices;'
[DllImport("gdi32.dll", EntryPoint = "DeleteObject")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DeleteObject([In] IntPtr hObject);
public ImageSource ImageSourceFromBitmap(Bitmap bmp)
{
var handle = bmp.GetHbitmap();
try
{
return Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
}
finally { DeleteObject(handle); }
}
这篇关于WPF - 将位图转换为 ImageSource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:WPF - 将位图转换为 ImageSource
基础教程推荐
- 从 C# 控制相机设备 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 将数据集转换为列表 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 如果条件可以为空 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
