在 WPF 中加载 BitmapImage 的源?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11771223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 04:49:04  来源:igfitidea点击:

loading the source of a BitmapImage in WPF?

c#wpfbitmapimage

提问by xarzu

In a silverlight app, I have a BitmapImage defined as System.Windows.Media.Imaging.BitmapImageand it as a method called "SetSource" where I can set the source like this:

在 Silverlight 应用程序中,我将 BitmapImage 定义为System.Windows.Media.Imaging.BitmapImage一个名为“ SetSource”的方法,我可以在其中像这样设置源:

BitmapImage bitmap = new BitmapImage();
System.IO.Stream stream = _scene.GetStream();
if (stream == null) return;
bitmap.SetSource(stream);

In a WPF application I have also have a Bitmap image defined as System.Windows.Media.Imaging.BitmapImagebut there is no SetSource method. How do I set the source in a WPF app like I do in a Silverlight app?

在 WPF 应用程序中,我还定义了一个位图图像,System.Windows.Media.Imaging.BitmapImage但没有 SetSource 方法。如何像在 Silverlight 应用程序中那样在 WPF 应用程序中设置源?

Also, it is a stream, not a string. It is not a URI. so "UriSource" method does not work. I tried this:

此外,它是一个流,而不是一个字符串。它不是一个 URI。所以“UriSource”方法不起作用。我试过这个:

        System.IO.Stream stream = _scene.GetStream();
        if (stream == null) return;
        BitmapImage bitmap = new BitmapImage();

        bitmap.UriSource = new Uri(stream.ToString());

And at runtime, it threw an error tha URI cannot be determined. Is the URI an identifier for the intranet? Are you sure that this is not a silverlight thing? I am doing a WPF application

并且在运行时,它抛出了一个无法确定 URI 的错误。URI 是 Intranet 的标识符吗?你确定这不是银光闪闪的东西吗?我正在做一个 WPF 应用程序

回答by Clemens

You'll have to set the BitmapImage.StreamSourceproperty:

您必须设置BitmapImage.StreamSource属性:

BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = _scene.GetStream();
bitmap.EndInit();

If you want to close the stream right after creating the bitmap, you would also have to set the BitmapCacheOption.OnLoadoption:

如果您想在创建位图后立即关闭流,您还必须设置BitmapCacheOption.OnLoad选项:

using (Stream stream = _scene.GetStream())
{
    bitmap.BeginInit();
    bitmap.CacheOption = BitmapCacheOption.OnLoad;
    bitmap.StreamSource = stream;
    bitmap.EndInit();
}

回答by Habib

You can use the constructorto specify the UriSource

您可以使用构造函数来指定UriSource

BitmapImage bmp = new BitmapImage(uriSource: new Uri());

Or you can use BitmapImage.StreamSourceproperty to set the StreamSource

或者你可以使用BitmapImage.StreamSource属性来设置 StreamSource