之前有個需求是在WPF中生成二維碼,用的是QRCoder。
QRCoder生成的是Bitmap,在wpf中需要轉換成ImageSource才能顯示。
之前的轉換方式是:
IntPtr hBitmap = qrCodeImage.GetHbitmap(); ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
之后客戶用了一段時間,出現內存不足的情況,找了好久,才找到原來是這里特別耗內存,每生成一次會占用100多M。
研究了下,是因為沒有釋放的問題。修改了下終於解決了這個問題。
[DllImport("gdi32.dll", EntryPoint = "DeleteObject")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool DeleteObject([In] IntPtr hObject); public ImageSource ImageSourceForBitmap(Bitmap bmp) { var handle = bmp.GetHbitmap(); try { ImageSource newSource = Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); DeleteObject(handle); return newSource; } catch (Exception ex) { DeleteObject(handle); return null; } }
單獨只用DeleteObject效果也不是特別好,最后再手動加個GC.Collect(),內存沒有再出現瘋狂增長。