我该如何从图像文件中加载BitmapSource
?
BitmapImage
类是BitmapSource
的非抽象子类,因此只需使用BitmapImage(Uri)
构造函数,并将该新实例传递给期望一个BitmapSource
对象的任何内容。System.Uri
所迷惑:一个Uri
不仅适用于http://
地址,还适用于本地文件系统路径和UNC共享等更多场景。所以这对我来说可行:
BitmapImage thisIsABitmapImage = new BitmapImage(new Uri("c:\\image.bmp"));
BitmapSource thisIsABitmapImageUpcastToBitmapSource = thisIsABitmapImage;
var stream = new MemoryStream(imageBytes);
var img = new System.Windows.Media.Imaging.BitmapImage();
img.BeginInit();
img.StreamSource = stream;
img.EndInit();
return img;
FileStream fileStream =
new FileStream(fileName, FileMode.Open, FileAccess.Read);
var img = new System.Windows.Media.Imaging.BitmapImage();
img.BeginInit();
img.StreamSource = fileStream;
img.EndInit();