Release handle on file. ImageSource from BitmapImage

前端 未结 2 1966
一生所求
一生所求 2020-12-05 13:54

How can I release the handle on this file?

img is of type System.Windows.Controls.Image

private void Load()
{
    ImageSource imageSrc = new BitmapIm         


        
相关标签:
2条回答
  • 2020-12-05 14:04

    Found the answer on MSDN Forum.

    Bitmap stream is not closed unless caching option is set as BitmapCacheOption.OnLoad. So you need something like this:

    public static ImageSource BitmapFromUri(Uri source)
    {
        var bitmap = new BitmapImage();
        bitmap.BeginInit();
        bitmap.UriSource = source;
        bitmap.CacheOption = BitmapCacheOption.OnLoad;
        bitmap.EndInit();
        return bitmap;
    }
    

    And when you get an ImageSource using the method above, source file will be immediately closed.

    see MSDN social forum

    0 讨论(0)
  • 2020-12-05 14:30

    I kept running into issues with this on a particularly troubling image. The accepted answer did not work for me.

    Instead, I used a stream to populate the bitmap:

    using (FileStream fs = new FileStream(path, FileMode.Open))
    {
        bitmap.BeginInit();
        bitmap.StreamSource = fs;
        bitmap.CacheOption = BitmapCacheOption.OnLoad;
        bitmap.EndInit();
    }
    

    This caused the file handle to be released.

    0 讨论(0)
提交回复
热议问题