3

Panelに を追加する必要があるImageため、次のコードを使用します。

var image = new Image();
var source = new BitmapImage();
source.BeginInit();
source.CacheOption = BitmapCacheOption.OnLoad;
source.StreamSource = new FileStream(filename, FileMode.Open);
source.EndInit();

// I close the StreamSource so I can load again the same file
source.StreamSource.Close();
image.Source = source;

問題は、画像ソースを使用しようとすると、次のようになることObjectDisposedExceptionです。

var source = ((BitmapImage)image.Source).StreamSource;

// When I use source I get the exception
using (var stream = new MemoryStream((int)(source.Length)))
{
    source.Position = 0;
    source.CopyTo(stream);
    // ...
}

ソースを閉じたために発生しますが、閉じないと同じファイルを再度読み込むことができません。

この問題を解決するにはどうすればよいですか (つまり、ソースを閉じて、同じファイルを複数回ロードできるようにし、例外を取得せずにソースを使用できるようにします)。

4

1 に答える 1

3

次の解決策がうまくいくはずです。

var image = new Image();
var source = new BitmapImage();
source.BeginInit();
source.CacheOption = BitmapCacheOption.OnLoad;

// Create a new stream without disposing it!
source.StreamSource = new MemoryStream();

using (var filestream = new FileStream(filename, FileMode.Open))
{
   // Copy the file stream and set the position to 0
   // or you will get a FileFormatException
   filestream.CopyTo(source.StreamSource);
   source.StreamSource.Position = 0;
}

source.EndInit();
image.Source = source;
于 2013-11-03T17:07:25.137 に答える