How can I load a BitmapSource
from an image file?
Asked
Active
Viewed 4.3k times
3 Answers
56
- The
BitmapImage
class is a non-abstract
subclass ofBitmapSource
, so just use theBitmapImage(Uri)
constructor and pass that new instance to anything that expects aBitmapSource
object. - Don't be confused by the fact the argument type is
System.Uri
: aUri
isn't just forhttp://
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
-
5But 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