Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display an image in WPF without holding the file open

Tags:

file

image

wpf

I'm working on an image management app in WPF that displays a number of images and allows the user to move them around the file system. The issue I've run into is that displaying a file with an <Image> element appears to hold the file open, so attempts to move or delete the file fail. Is there a way to manually ask WPF to unload or release a file so it can be moved? Or is there a method of displaying images that doesn't hold the file open? Viewer Xaml below:

<ListBox x:Name="uxImages" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel Orientation="Horizontal" />
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>

            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Border Margin="4">
                        <Image Source="{Binding}" Width="150" Height="150"/>
                    </Border>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
like image 924
James Cadd Avatar asked Nov 19 '09 14:11

James Cadd


1 Answers

What is the ItemsSource of your ListBox ? A list of strings containing the image paths ?

Instead of implicitly using the built-in converter from string to ImageSource, use a custom converter to close the stream after you load the image :

public class PathToImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string path = value as string;
        if (path != null)
        {
            BitmapImage image = new BitmapImage();
            using (FileStream stream = File.OpenRead(path))
            {
                image.BeginInit();
                image.StreamSource = stream;
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.EndInit(); // load the image from the stream
            } // close the stream
            return image;
        }
    }
}
like image 81
Thomas Levesque Avatar answered Sep 20 '22 12:09

Thomas Levesque