我正在使用一个使用BitmapSource的WPF应用程序,但是我需要进行一些操作,但是我需要对System.Drawing.Bitmaps进行一些操作。
应用程序在运行时内存使用量会增加。
我已经将内存泄漏的范围缩小到以下代码:
private BitmapSource BitmaptoBitmapsource(System.Drawing.Bitmap bitmap)
{
BitmapSource bms;
IntPtr hBitmap = bitmap.GetHbitmap();
BitmapSizeOptions sizeOptions = BitmapSizeOptions.FromEmptyOptions();
bms = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, sizeOptions);
bms.Freeze();
return bms;
}
我假设这是非托管内存没有被正确处理,但我似乎找不到任何手动处理的方法。提前感谢您的帮助!
亚历克斯
发布于 2011-12-29 16:10:24
你需要在你的hBitmap
上调用DeleteObject(...)
。请参阅:http://msdn.microsoft.com/en-us/library/1dz311e4.aspx
private BitmapSource BitmaptoBitmapsource(System.Drawing.Bitmap bitmap)
{
BitmapSource bms;
IntPtr hBitmap = bitmap.GetHbitmap();
BitmapSizeOptions sizeOptions = BitmapSizeOptions.FromEmptyOptions();
bms = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap,
IntPtr.Zero, Int32Rect.Empty, sizeOptions);
bms.Freeze();
// NEW:
DeleteObject(hBitmap);
return bms;
}
发布于 2011-12-29 16:10:30
您需要在hBitmap上调用DeleteObject(hBitmap)
:
private BitmapSource BitmaptoBitmapsource(System.Drawing.Bitmap bitmap) {
BitmapSource bms;
IntPtr hBitmap = bitmap.GetHbitmap();
BitmapSizeOptions sizeOptions = BitmapSizeOptions.FromEmptyOptions();
try {
bms = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, sizeOptions);
bms.Freeze();
} finally {
DeleteObject(hBitmap);
}
return bms;
}
发布于 2011-12-29 16:11:49
https://stackoverflow.com/questions/8670151
复制相似问题