How to force Image control to close the file that it opens in wpf

為{幸葍}努か 提交于 2019-12-01 19:11:53

You could use a binding converter like below that loads an image directly to memory cache by setting BitmapCacheOption.OnLoad. The file is loaded immediately and not locked afterwards.

<Image Source="{Binding ...,
                Converter={StaticResource local:StringToImageConverter}}"/>

The converter:

public class StringToImageConverter : IValueConverter
{
    public object Convert(
        object value, Type targetType, object parameter, CultureInfo culture)
    {
        object result = null;
        var path = value as string;

        if (!string.IsNullOrEmpty(uri))
        {
            var image = new BitmapImage();
            image.BeginInit();
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.UriSource = new Uri(path);
            image.EndInit();
            result = image;
        }

        return result;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

Even better, load the BitmapImage directly from a FileStream:

public object Convert(
    object value, Type targetType, object parameter, CultureInfo culture)
{
    object result = null;
    var path = value as string;

    if (!string.IsNullOrEmpty(path) && File.Exists(path))
    {
        using (var stream = File.OpenRead(path))
        {
            var image = new BitmapImage();
            image.BeginInit();
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.StreamSource = stream;
            image.EndInit();
            result = image;
        }
    }

    return result;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!