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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!