如何将BitmapImage的源设置为Stream?

时间:2012-09-01 23:15:53

标签: wpf stream bitmapimage

我正在尝试在WPF中显示图像。我用这个:

            Stream fs = File.Open(path, FileMode.Open);

            BitmapImage bmp = new BitmapImage();
            bmp.BeginInit();
            bmp.StreamSource = fs;
            bmp.EndInit();
            img.Source = bmp;
            fs.Close();

无论是否关闭流都无效。什么工作:

            BitmapImage bmp = new BitmapImage(new Uri(path));
            img.Source = bmp;

我会使用第二种方法,除了我需要关闭流。这有什么问题?

1 个答案:

答案 0 :(得分:1)

对于将来寻找此事的人:我在设置StreamSource之前添加以下行来修复此问题:      bmp.CacheOption = BitmapCacheOption.OnLoad;

完整代码:

            BitmapImage bmp = new BitmapImage();
            bmp.BeginInit();
            bmp.CacheOption = BitmapCacheOption.OnLoad;
            bmp.StreamSource = fs;
            bmp.EndInit();
            img.Source = bmp;
相关问题