1. 程式人生 > >WPF Bitmap轉成Imagesource的效能優化

WPF Bitmap轉成Imagesource的效能優化

之前有個需求是在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(),記憶體沒有再出現瘋狂增長。