Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

View Image file without locking it. (Copy to memory?)

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"

like image 831
Usta Avatar asked Jan 31 '12 23:01

Usta


2 Answers

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;
like image 72
Marcus Avatar answered Oct 14 '22 10:10

Marcus


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;
like image 24
Chris Shain Avatar answered Oct 14 '22 10:10

Chris Shain