天天看点

C# WPF Image Source 频繁切换导致垃圾回收不及时导致内存占用不断增加的问题

[DllImport("gdi32.dll", SetLastError = true)]
        private static extern bool DeleteObject(IntPtr hObject);

        /// <summary>
        /// 转Bitmap
        /// </summary>
        /// <param name="srcFile">源文件</param>
        /// <returns></returns>
        public static BitmapSource BitmapToBitmapImage(string srcFile)
        {
            if (!File.Exists(srcFile))
                return null;
            System.Drawing.Bitmap bmp = System.Drawing.Bitmap.FromFile(srcFile) as System.Drawing.Bitmap;
            var ptr = bmp.GetHbitmap();
            var source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                  ptr, IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
            source.Freeze();
            bmp.Dispose();
            DeleteObject(ptr);
            return source;

            // 下面的代码会导致内存回收不及时,内存很长时间才会回收
            //BitmapImage image = new BitmapImage();
            //image.BeginInit();
            //using (MemoryStream stream = new MemoryStream(File.ReadAllBytes(srcFile)))
            //{
            //    //bitmap.Save(stream, ImageFormat.Bmp); // 坑点:格式选Bmp时,不带透明度
            //    //stream.Position = 0;
            //    // According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed."
            //    // Force the bitmap to load right now so we can dispose the stream.
            //    image.CacheOption = BitmapCacheOption.OnLoad;
            //    image.StreamSource = stream;
            //    image.EndInit();
            //    image.Freeze();
            //}
            //return image;
        }