
CreateBitmapSourceFromHBitmap()
WPF 的 CreateBitmapSourceFromHBitmap() 提供了一种将 System.Drawing.Bitmap 图像集成到 WPF 应用程序中的便捷方法。 但是,使用不当可能会导致严重的内存泄漏。
重复调用CreateBitmapSourceFromHBitmap()而不进行适当的清理会导致应用程序内存消耗稳步增加。这是因为未能释放与 System.Drawing.Bitmap 对象关联的底层 GDI 位图资源。
为防止内存泄漏,请在与 CreateBitmapSourceFromHBitmap() 一起使用后显式删除 GDI 位图句柄。 以下代码演示了这一关键步骤:
<code class="language-csharp">[DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(1000, 1000))
{
IntPtr hBitmap = bmp.GetHbitmap();
try
{
var source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
// Use the 'source' BitmapSource here...
}
finally
{
DeleteObject(hBitmap);
}
}</code>using 语句确保 System.Drawing.Bitmap 得到正确处理,即使发生异常也是如此。
System.Drawing.Bitmap 对象在 之前BitmapSource 被处置,以防止潜在的跨线程访问问题。Imaging.CreateBitmapSource() 作为更好的替代方案。该方法本质上管理底层位图资源,无需手动清理并降低内存泄漏的风险。以上是使用WPF的CreateBitmapSourceFromHBitmap()时如何防止内存泄漏?的详细内容。更多信息请关注PHP中文网其他相关文章!