从文件创建BitmapSource

31

我该如何从图像文件中加载BitmapSource

3个回答

57
  • BitmapImage类是BitmapSource的非抽象子类,因此只需使用BitmapImage(Uri)构造函数,并将该新实例传递给期望一个BitmapSource对象的任何内容。
  • 不要被参数类型为System.Uri所迷惑:一个Uri不仅适用于http://地址,还适用于本地文件系统路径和UNC共享等更多场景。

所以这对我来说可行:

BitmapImage thisIsABitmapImage = new BitmapImage(new Uri("c:\\image.bmp"));

BitmapSource thisIsABitmapImageUpcastToBitmapSource = thisIsABitmapImage;

7
你可以将图像的字节从磁盘读入到一个字节数组中,然后创建你的BitmapImage对象。
var stream = new MemoryStream(imageBytes);
var img = new System.Windows.Media.Imaging.BitmapImage();

img.BeginInit();
img.StreamSource = stream;
img.EndInit();

return img;

6
但是这会泄漏MemoryStream!你需要将CacheOption设置为OnLoad,并在使用后处理该流。 - Vlad
据我所知,没有任何理由去释放MemoryStream,它只是一个字节数组的包装器,而该类上的dispose方法具有空实现。 - caesay

5
代码如下:
FileStream fileStream = 
    new FileStream(fileName, FileMode.Open, FileAccess.Read);

var img = new System.Windows.Media.Imaging.BitmapImage();
img.BeginInit();
img.StreamSource = fileStream;
img.EndInit();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接