WPF BitmapImage 占用资源无法释放、无法删除问题

使用Image控件显示图片后,虽然自己释放了图片资源,Image.Source =null 了一下,但是图片实际没有释放。
解决方案:修改加载方式~
        public static BitmapImage GetImage(string imagePath)
        {
            BitmapImage bitmap = new BitmapImage();
            if (File.Exists(imagePath))
            {
                bitmap.BeginInit();
                bitmap.CacheOption = BitmapCacheOption.OnLoad;
                using (Stream ms = new MemoryStream(File.ReadAllBytes(imagePath)))
                {
                    bitmap.StreamSource = ms;
                    bitmap.EndInit();
                    bitmap.Freeze();
                }
            }
            return bitmap;
        }
  //使用时直接通过调用此方法获得Image后立马释放掉资源
       ImageBrush berriesBrush = new ImageBrush();   
       berriesBrush.ImageSource = GetImage(path); //path为图片的路径        
       this.Background = berriesBrush;

posted @ 2018-08-03 14:04  QianTM  阅读(1302)  评论(0编辑  收藏  举报