如何在WPF中从图像源中释放图像

时间:2013-06-04 01:24:08

标签: c# wpf image

正在加载如下图像

XAML

<Image Stretch="None" Grid.Row="16" Height="70" HorizontalAlignment="Left" Name="imgThumbnail" VerticalAlignment="Top" Width="70" Grid.RowSpan="3" Margin="133,1,0,0" Grid.Column="2" Grid.ColumnSpan="2" />

代码隐藏

if (Path.GetFileNameWithoutExtension(filePath).ToLower().Contains(slugName.ToLower() + "_70x70"))
{
    imgThumbnail.BeginInit();
    imgThumbnail.Stretch = Stretch.UniformToFill;
    imgThumbnail.Source = new BitmapImage(new Uri(filePath));
    imgThumbnail.EndInit();
    count = count + 1;
}

上面的代码工作正常,现在我的缩略图旁边有一个删除按钮,如果删除按钮,我想删除源位置的所有图像。

以下是删除图像文件的代码

internal int Remove(string slugName, DirectoryInfo outputFolder)
{
    Helper.MetadataView.imgThumbnail.Source = null;

    foreach (string filePath_ToBeDeleted in filePathList_ToBeDeleted)
    {
        if (File.Exists(filePath_ToBeDeleted))
        {
            Helper.MetadataView.imgThumbnail.IsEnabled = false;
            File.Delete(filePath_ToBeDeleted);
            count += 1;
            }
        }
        return count;
    }
    return 0; // slugName == null
}

我尝试将源为null并删除,但它会抛出异常,如下所示

该进程无法访问文件'\ serv1 \ Dev \ Images \ 730_Test4_0406_70x70.jpg',因为它正由另一个进程使用。

我不确定如何处置,请有人指导我。

2 个答案:

答案 0 :(得分:35)

如果要删除或移动它,则不应直接在应用程序中使用Image

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

相反,这样做:

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

更多阅读this

答案 1 :(得分:0)

要获得良好的代码重用,可以使用绑定转换器:

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();
        }
    }
}

例如,有一个用于绑定的字符串

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

在UI中使用转换器,在我的例子中,使用的是名为“ 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>