【发布时间】:2022-03-04 10:41:53
【问题描述】:
如何从图像文件加载BitmapSource?
【问题讨论】:
如何从图像文件加载BitmapSource?
【问题讨论】:
BitmapImage class is a non-asbtract subclass of BitmapSource,所以只需使用 new BitmapImage(Uri) 构造函数并将新实例传递给任何需要 BitmapSource 对象的对象。System.Uri 的事实所迷惑:Uri 不仅适用于 http:// 地址,还适用于本地文件系统路径和 UNC 共享等。李>
所以这对我有用:
BitmapImage thisIsABitmapImage = new BitmapImage(new Uri("c:\\image.bmp"));
BitmapSource thisIsABitmapImageUpcastToBitmapSource = thisIsABitmapImage;
【讨论】:
您可以将图像的字节从磁盘读取到字节数组中,然后创建您的 BitmapImage 对象。
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();
【讨论】: