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

I want to be able to open / view an image (.jpg) without locking the file. Basically, I have a program that allows the user to select an image that will overwrite the image. But the problem is that I am displaying an image that is being overwritten. So, how do I upload an image without blocking it?

This is the code that I have to install right now.

Image1.Source = new BitmapImage( new Uri( myFilePath ) ) ); 

myFilePath is equal to a line that resembles "C: \ Users * \ My Pictures \ Sample.jpg"

+4
source share
3 answers

myBitmap.CacheOption = BitmapCacheOption.OnLoad is the line you are looking for. It "caches the entire image into memory at boot time. All requests for image data are populated from the storage." From MSDN

Something like that:

 BitmapImage bmi = new BitmapImage(); bmi.BeginInit(); bmi.UriSource = new Uri(myFilePath); bmi.CacheOption = BitmapCacheOption.OnLoad; bmi.EndInit(); Image1.Source = bmi; 
+8
source

I think StreamSource is the property you are looking for. You read the image in a MemoryStream and then set the MemoryStream as a BitmapImage StreamSource value:

 var memStream = new MemoryStream(File.ReadAllBytes(myFilePath)); Image1.Source = new BitmapImage() { StreamSource = memStream }; 

EDIT: I tried this code, and it looks like you need to call BitmapImage.BeginInit and BitmapImage.EndInit around the Source setting:

 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; 
+1
source

When you open a file, you can also select the proportion of the file to determine its beaviour when another program requires this file:

(from msdn: http://msdn.microsoft.com/en-us/library/y973b725.aspx )

File.Open Method (String, FileMode, FileAccess, ** FileShare ** )

Parameters
way
Type: System.String
File to open.

Mode
Type: System.IO.FileMode
A FileMode value that indicates whether the file is created if it does not exist and determines whether the contents of existing files are saved or overwritten.


Access Type: System.IO.FileAccess
A FileAccess value that indicates the operations that can be performed in the file.

* share
* Type: System.IO.FileShare *
The FileShare value, which determines the type of access to other streams, belongs to the file.

0
source

Source: https://habr.com/ru/post/1394083/


All Articles