当前位置: 移动技术网 > IT编程>开发语言>.net > WPF Bitmap转成Imagesource的性能优化

WPF Bitmap转成Imagesource的性能优化

2019年01月08日  | 移动技术网IT编程  | 我要评论

刘惠璞老婆刘康佳,麦博雅皮士h20,cri环球旅游频道

之前有个需求是在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(),内存没有再出现疯狂增长。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网