从System.Drawing.Bitmap加载WPF BitmapImage
时间:2020-03-06 14:22:22 来源:igfitidea点击:
我有一个System.Drawing.Bitmap的实例,并想以System.Windows.Media.Imaging.BitmapImage的形式将其提供给我的WPF应用程序。
最好的方法是什么?
解决方案
最简单的事情是,我们可以直接从文件中制作WPF位图。
否则,我们将不得不使用System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap。
我在图像处理供应商处工作,并为WPF编写了一个适配器,以适应我们的图像格式,类似于System.Drawing.Bitmap。
我写了这个知识库,向我们的客户解释:
http://www.atalasoft.com/kb/article.aspx?id=10156
那里有执行此操作的代码。我们需要用Bitmap替换AtalaImage并执行我们正在做的等效操作-它应该非常简单。
感谢Hallgrim,这是我最终得到的代码:
ScreenCapture = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( bmp.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(width, height));
我也结束了绑定到BitmapSource而不是原始问题中的BitmapImage的绑定
如何从MemoryStream加载它?
using(MemoryStream memory = new MemoryStream())
{
bitmap.Save(memory, ImageFormat.Png);
memory.Position = 0;
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
}
我知道已经回答了,但是这里有几个扩展方法(用于.NET 3.0+)可以进行转换。 :)
/// <summary>
/// Converts a <see cref="System.Drawing.Image"/> into a WPF <see cref="BitmapSource"/>.
/// </summary>
/// <param name="source">The source image.</param>
/// <returns>A BitmapSource</returns>
public static BitmapSource ToBitmapSource(this System.Drawing.Image source)
{
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(source);
var bitSrc = bitmap.ToBitmapSource();
bitmap.Dispose();
bitmap = null;
return bitSrc;
}
/// <summary>
/// Converts a <see cref="System.Drawing.Bitmap"/> into a WPF <see cref="BitmapSource"/>.
/// </summary>
/// <remarks>Uses GDI to do the conversion. Hence the call to the marshalled DeleteObject.
/// </remarks>
/// <param name="source">The source bitmap.</param>
/// <returns>A BitmapSource</returns>
public static BitmapSource ToBitmapSource(this System.Drawing.Bitmap source)
{
BitmapSource bitSrc = null;
var hBitmap = source.GetHbitmap();
try
{
bitSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
}
catch (Win32Exception)
{
bitSrc = null;
}
finally
{
NativeMethods.DeleteObject(hBitmap);
}
return bitSrc;
}
和NativeMethods类(以安抚FxCop)
/// <summary>
/// FxCop requires all Marshalled functions to be in a class called NativeMethods.
/// </summary>
internal static class NativeMethods
{
[DllImport("gdi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DeleteObject(IntPtr hObject);
}

