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(),内存没有再出现疯狂增长。

posted @ 2019-01-07 16:49  liuyong111  阅读(1573)  评论(2编辑  收藏  举报