天天看點

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;
        }