How to free the memory after the BitmapImage is no longer needed?

后端 未结 4 786
悲哀的现实
悲哀的现实 2020-11-30 07:12

First, I load a BitmapImage on the Image control on the Window. Second, I work with the Image control and then close the

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 07:18

    I believe the solution you are looking for is at http://www.ridgesolutions.ie/index.php/2012/02/03/net-wpf-bitmapimage-file-locking/. In my case, I was trying to find a way to delete the file after it was created, but it appears to be a solution to both issues.

    Doesn't free up memory:

    var bitmap = new BitmapImage(new Uri(imageFilePath));
    

    Frees up memory, and allows file to be deleted:

    var bitmap = new BitmapImage(); 
    var stream = File.OpenRead(imageFilePath);
    
    bitmap.BeginInit();
    bitmap.CacheOption = BitmapCacheOption.OnLoad;
    bitmap.StreamSource = stream;
    bitmap.EndInit();
    stream.Close();
    stream.Dispose();
    

    Optionally, also freeze the BitmapImage:

    bitmap.Freeze();
    

提交回复
热议问题