BitmapImage in WPF does lock file
Asked Answered
O

4

21

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

Ogpu answered 21/6, 2011 at 18:38 Comment(2)
There are also memory issues to take a look at. See #6272391Chiang
Thanks. Do you want me to say, to not try to cache all file if not really possible with your link?Ogpu
C
42

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()
Cherubini answered 21/6, 2011 at 18:47 Comment(2)
Thanks for your quick reply also regarding my keywords and VB instead of C#! Works great now!Ogpu
Is there a way to do this strictly using XAML.Britain
C
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;
Conformance answered 21/6, 2011 at 18:49 Comment(3)
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.Ogpu
Now, who owns the MemoryStream object instance and is responsible for disposing it?Chartres
Anyway... How to unlock file and delete it?Foliolate
B
2
BitmapFrame.Create(new Uri(filePath), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
Blandishments answered 4/9, 2014 at 12:25 Comment(1)
Best solution in 1 line. Thanks! I used MemoryStream before, but this looks more simple.Urinate
J
2

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!

Jerriejerrilee answered 15/9, 2014 at 12:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.