在使用文件选择器更改图像的ImageSource时,弹出提示该文件正在使用中

问题描述 投票:0回答:2

我有一个具有默认ImageSource的图像,在使用文件选择器拾取新图像时,它加载正常,然后再次拾取先前使用的文件,弹出窗口提示该文件仍在使用中。每次选择新图像时,它都可以正常工作。有什么方法可以关闭或处置以前选择的文件或其ImageSource?

 <Image x:Name="image" Source="Assets\RoadView.jpeg"></Image>

  private void change_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Filter = "Image Files ( *.png, *.bmp *.jpg, *.gif, *.tif)|*.png;*.bmp;*.jpg;*.gif;*.tif";
        openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);

        if (openFileDialog.ShowDialog() == true)
        {
            Stream stream = File.Open(openFileDialog.FileName, FileMode.Open);
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = stream;
            bitmapImage.EndInit();
            image.Source = bitmapImage;
        }
    }
wpf image imagesource
2个回答
0
投票
默认情况下,将缓存BitMapImage。

尝试添加行:

bitmapImage.CacheOption = BitmapCacheOption.OnLoad;

不确定确切的位置,最好在endinit之前。

https://docs.microsoft.com/en-us/dotnet/api/system.windows.media.imaging.bitmapimage.cacheoption?view=netframework-4.8

“如果希望关闭用于创建BitmapImage的流,请将CacheOption设置为BitmapCacheOption.OnLoad。默认的OnDemand缓存选项将保留对该流的访问,直到需要该图像为止,并且清理由垃圾收集器处理。”] >


0
投票
您不关闭FileStream,因此文件保持打开状态,无法再次打开。
© www.soinside.com 2019 - 2024. All rights reserved.