20

I use:

Dim bmi As New BitmapImage(New Uri(fiInfo.FullName, UriKind.Absolute))
bmi.CacheOption = BitmapCacheOption.OnLoad

this does not Use OnLoad And file still is locked to overwrite on harddisk. Any idea how to unlock?

Regards

Community
  • 1
  • 1
Nasenbaer
  • 4,810
  • 11
  • 53
  • 86
  • There are also memory issues to take a look at. See http://stackoverflow.com/questions/6271891/net-memory-issues-loading-40-images-memory-not-reclaimed-potentially-due-to-l/6271982#6271982 – Oppositional Jun 21 '11 at 18:53
  • Thanks. Do you want me to say, to not try to cache all file if not really possible with your link? – Nasenbaer Jun 21 '11 at 18:58

4 Answers4

41

As shown in the question you link to, you'd need to call BeginInit and EndInit, like so as well as set the UriSource property:

Dim bmi As New BitmapImage()
bmi.BeginInit()
bmi.CacheOption = BitmapCacheOption.OnLoad
bmi.UriSource = New Uri(fiInfo.FullName, UriKind.Absolute)
bmi.EndInit()
CodeNaked
  • 40,753
  • 6
  • 122
  • 148
9

Read the BitmapImage from file and rewrite it with a MemoryStream:

MemoryStream ms = new MemoryStream();
BitmapImage bi = new BitmapImage();
byte[] bytArray = File.ReadAllBytes(@"test.jpg");
ms.Write(bytArray, 0, bytArray.Length);ms.Position = 0;
bi.BeginInit();
bi.StreamSource = ms;
bi.EndInit();
image.Source = bi;
Navid Rahmani
  • 7,848
  • 9
  • 39
  • 57
  • Thank you Navid for your quick reply. I see that will work that way as far as I see. I am using the `bmi.EndInit()` methode + `OnLoad ` now which is a little more simple in my case. – Nasenbaer Jun 21 '11 at 18:56
  • Now, who owns the MemoryStream object instance and is responsible for disposing it? – Henrik May 09 '12 at 14:30
  • 1
    Anyway... How to unlock file and delete it? – NoWar Oct 26 '12 at 18:14
3

I had a similar problem and I solved using this method: (it's a personalization of an answer here)

    public static BitmapImage BitmapFromUri(Uri source)
    {
        var bitmap = new BitmapImage();
        bitmap.BeginInit();
        bitmap.UriSource = source;
        bitmap.CacheOption = BitmapCacheOption.OnLoad;
        bitmap.EndInit();
        return bitmap;
    }

You can open the image like this:

BitmapImage bimg = BitmapFromUri(new Uri(some_URI));

And it releases the image immediatly after loading it.

Hope it can helps!

Community
  • 1
  • 1
smukamuka
  • 1,442
  • 1
  • 15
  • 23
1
BitmapFrame.Create(new Uri(filePath), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
Andreas
  • 3,843
  • 3
  • 40
  • 53