I want to be able to open/view a image (.jpg) without locking the file. Basically I have a program that lets the user choose a picture that will overwrite a picture. But the problem is that I display the image that is being overwritten. So how do I load an image without locking it?
This is the code I have to set the image right now
Image1.Source = new BitmapImage( new Uri( myFilePath ) ) );
myFilePath is equal to a string that would something like "C:\Users*\My Pictures\Sample.jpg"
myBitmap.CacheOption = BitmapCacheOption.OnLoad
is the line you're looking for. It "caches the entire image into memory at load time. All requests for image data are filled from the memory store." From MSDN
Something like this:
BitmapImage bmi = new BitmapImage();
bmi.BeginInit();
bmi.UriSource = new Uri(myFilePath);
bmi.CacheOption = BitmapCacheOption.OnLoad;
bmi.EndInit();
Image1.Source = bmi;
I think that StreamSource is the property you are looking for. You'd read the image into a MemoryStream, then set the MemoryStream as the value of the BitmapImage's StreamSource:
var memStream = new MemoryStream(File.ReadAllBytes(myFilePath));
Image1.Source = new BitmapImage() { StreamSource = memStream };
EDIT: I've tried this code, and it looks like you need to call BitmapImage.BeginInit and BitmapImage.EndInit around setting the Source:
var memStream = new MemoryStream(File.ReadAllBytes(@"C:\Users\Public\Pictures\Sample Pictures\Koala.jpg"));
var img = new BitmapImage();
img.BeginInit();
img.StreamSource = memStream;
img.EndInit();
myImage.Source = img;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With