How to release Image from Image Source in WPF

前端 未结 2 1876
温柔的废话
温柔的废话 2020-12-16 14:09

Am loading image like below

XAML



        
相关标签:
2条回答
  • 2020-12-16 14:33

    To have a good code-reuse a binding converter could be used:

    namespace Controls
    {
        [ValueConversion(typeof(String), typeof(ImageSource))]
        public class StringToImageSourceConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                if (!(value is string valueString))
                {
                    return null;
                }
                try
                {
                    ImageSource image = BitmapFrame.Create(new Uri(valueString), BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.OnLoad);
                    return image;
                }
                catch { return null; }
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                throw new NotImplementedException();
            }
        }
    }
    

    And there is a string for binding, for example

    public string MyImageString { get; set; } = @"C:\test.jpg"
    

    And in the UI the converter is used, in my case from the Library named "Controls"

    <Window x:Class="MainFrame"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:controls="clr-namespace:Controls;assembly=Controls">
        <Window.Resources>
            <controls:StringToImageSourceConverter x:Key="StringToImageSourceConverter" />
        </Window.Resources>
        <Grid>
            <Image Source="{Binding MyImageString, Converter={StaticResource StringToImageSourceConverter}}" />
        </Grid>
    </Window>
    
    0 讨论(0)
  • 2020-12-16 14:35

    You should not use that Image directly in your application if you want to delete or move it.

    imgThumbnail.Source = new BitmapImage(new Uri(filePath));
    

    Instead, do this:

    BitmapImage image = new BitmapImage();
    image.BeginInit();
    image.CacheOption = BitmapCacheOption.OnLoad;
    image.UriSource = new Uri(filePath);
    image.EndInit();
    imgThumbnail.Source = image;
    

    For more read this

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