31
votes

How can I load a BitmapSource from an image file?

3

3 Answers

52
votes

This works for me:

BitmapSource bSource = new BitmapImage(new Uri("c:\\image.bmp"));
BitmapImage bImage = new BitmapImage(new Uri("c:\\image.bmp"));
8
votes

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;
4
votes

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();