イメージのパスを取得し、それをWPF アプリケーションのOpenFileDialog
イメージ ソース プロパティに設定するために使用します。imgSelected.Source = new BitmapImage(new Uri(filenameSteg, UriKind.Absolute));
問題は、そのファイルを後でもう一度開く必要があるということですが、ファイルが別のプロセスで使用されているため( System.IO.IOException
-> The process cannot access the file
pathToFile because it is being used by another process.
)、開くことができません。
後でアクセスする必要があるコードは次のとおりです。
bitmapSource = JpegBitmapDecoder.Create(File.Open(filenameSteg, FileMode.Open),
BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames[0];
これbitmapSource
は、その画像をに渡すために使用され、WriteableBitmap
そこからピクセルを通過します。
OpenFileDialog で開かれたFileを破棄する方法はありますか?
IDisposable にキャストしたり、using ブロックを使用したりしようとしましたが、これは永続的です。
編集 :
1-これを試しました(@ctacke回答):
using (var stream = File.Open(filenameSteg, FileMode.Open)){
bitmapSource = JpegBitmapDecoder.Create(stream, BitmapCreateOptions.None,
BitmapCacheOption.OnLoad).Frames[0];}
filenameSteg
しかし、プロセスが別のプロセスによって既に使用されているというエラーが表示されます。これは、プロセスが後で破棄されても、同じファイル ( )を開こうとしているからですOpenFileDialog
。(または、少なくとも、それは私がそれを見る方法です。)
2-次にこれを試しました(@ctacke推奨リンクに基づく:
using (FileStream fileStream = new FileStream(filenameSteg+1, FileMode.Create)){
MemoryStream memoryStream = new MemoryStream();
BitmapImage bi = new BitmapImage();
byte[] fileBytes = File.ReadAllBytes(filenameSteg);
memoryStream.Write(fileBytes, 0, fileBytes.Length);
memoryStream.Position = 0;
bi.BeginInit();
bi.StreamSource = memoryStream;
bi.EndInit();
bitmapSource = bi;}
注:ここで を求めていることに注意してくださいfilenameSteg +1
。これは、メソッドの残りの部分をテストしたかったため、ファイルのコピーを作成し、その名前に 1 を追加しただけです。そうは言っても、filenameSteg
実際に使用すると、すでに使用されているという同じエラーが表示されましたが、以前にOpenFileDialog
.
3 - 開いた画像を破棄する必要のない別のアプローチを考えました:
で初めて画像を開くとき、画像OpenFileDialog
のバイト配列を変数に格納して、とバイト配列WriteableBitmap
を使用して を作成できるようにBitmapFactory
します。
// This is in the OpenFileDialog. It is where I stock the image "pixels" in a byte array.
bytesArrayImage = File.ReadAllBytes(filenameSteg);
//And then later when I needed the WriteableBitmap, I used the byte array and the BitmapFactory
//imgSelected being the Image containing the image I opened in the OpenFileDialog, I used it's
//width and height
wb = BitmapFactory.New(Convert.ToInt32(imgSelected.Width),
Convert.ToInt32(imgSelected.Height)).FromByteArray(bytesArrayImage);
このアプローチの問題は、一部の画像が正常に機能し、バイト配列を使用して を作成してそのWriteableBitmap
ピクセルを通過できることですが、それ以外の場合はAccessViolationException
: と表示されますAttempted to read or write protected memory. This is often an indication that other memory is corrupt.
。つまり、破棄の問題を回避しようとすると、別の問題が発生しました。