in4man
in4man

Reputation: 361

BitmapSource from file

How can I load a BitmapSource from an image file?

Upvotes: 31

Views: 45925

Answers (3)

iulian3000
iulian3000

Reputation: 1380

  • 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;

Upvotes: 58

sergtk
sergtk

Reputation: 10974

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

Upvotes: 5

ChrisNel52
ChrisNel52

Reputation: 15173

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;

Upvotes: 7

Related Questions