none
How to dispose a System.Windows.Media.ImageSource

    Question

  • Hi there,

    I've got a problem in a WPF solution.

    I created a XAML Image (System.Windows.Controls.Image) and in the C# code I defined the ImageSource.

    myImage.Source = (ImageSource)s.ConvertFromString("images/testimage1.jpg", null);
    Now, the imagefile is locked.

    If I change the ImageSource like

    myImage.Source = (ImageSource)s.ConvertFromString("images/testimage2.jpg", null);
    both images are locked. Now the question: How may I dispose the old ImageSource of testimage1.jpg so that I can access it. E.g. delete it or something else. At the moment I have to close the application.

    Thanks for help.
    Best regards,
    Cat
    Wednesday, August 26, 2009 12:23 PM

Answers

  • Bitmap stream is not closed unless caching option is set as BitmapCacheOption.OnLoad. So you need something like this:

    public static ImageSource BitmapFromUri(Uri source)
    {
        var bitmap = new BitmapImage();
        bitmap.BeginInit();
        bitmap.UriSource = source;
        bitmap.CacheOption = BitmapCacheOption.OnLoad;
        bitmap.EndInit();
        return bitmap;
    }
    And when you get an ImageSource using the method above, source file will be immediately closed.
    • Marked as answer by Catscratch296 Thursday, August 27, 2009 7:34 AM
    Wednesday, August 26, 2009 1:19 PM

All replies

  • Bitmap stream is not closed unless caching option is set as BitmapCacheOption.OnLoad. So you need something like this:

    public static ImageSource BitmapFromUri(Uri source)
    {
        var bitmap = new BitmapImage();
        bitmap.BeginInit();
        bitmap.UriSource = source;
        bitmap.CacheOption = BitmapCacheOption.OnLoad;
        bitmap.EndInit();
        return bitmap;
    }
    And when you get an ImageSource using the method above, source file will be immediately closed.
    • Marked as answer by Catscratch296 Thursday, August 27, 2009 7:34 AM
    Wednesday, August 26, 2009 1:19 PM
  • Hi,

    thanks a lot. That was the solution.

    Thank you!
    Thursday, August 27, 2009 7:34 AM