31

How can I load a BitmapSource from an image file?

Rudi Visser
  • 21,350
  • 5
  • 71
  • 97
in4man
  • 351
  • 1
  • 3
  • 6

3 Answers3

56
  • The BitmapImage class is a non-abstract subclass of BitmapSource, so just use the BitmapImage(Uri) constructor and pass that new instance to anything that expects a BitmapSource object.
  • Don't be confused by the fact the argument type is System.Uri: a Uri isn't just for http:// addresses, but it's also suitable for local filesystem paths and UNC shares, and more.

So this works for me:

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

BitmapSource thisIsABitmapImageUpcastToBitmapSource = thisIsABitmapImage;
Bradley Grainger
  • 27,458
  • 4
  • 91
  • 108
iulian3000
  • 1,270
  • 13
  • 26
8

You can read the bytes of the image from disk into a byte array and then create your BitmapImage object.

var stream = new MemoryStream(imageBytes);
var img = new System.Windows.Media.Imaging.BitmapImage();

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

return img;
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
ChrisNel52
  • 14,655
  • 3
  • 30
  • 36
  • 5
    But this leaks MemoryStream! You need to set CacheOption = OnLoad and dispose the stream afterwards. – Vlad Aug 28 '15 at 12:08
  • As far as I know, there is no reason to ever dispose a MemoryStream, it's just a wrapper around a byte array and the dispose method on that class has an empty implementation. – caesay Nov 13 '20 at 10:37
5

The code follows:

FileStream fileStream = 
    new FileStream(fileName, FileMode.Open, FileAccess.Read);

var img = new System.Windows.Media.Imaging.BitmapImage();
img.BeginInit();
img.StreamSource = fileStream;
img.EndInit();
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
sergtk
  • 10,714
  • 15
  • 75
  • 130