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(),內存沒有再出現瘋狂增長。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM