I am trying to create a BitmapImage from a byte array which is returned by a service.
My code is:
using (sc = new ServiceClient()) { using (MemoryStream ms = new MemoryStream(sc.GetImage())) { Display = new BitmapImage(); Display.BeginInit(); Display.StreamSource = ms; Display.EndInit(); } } However, an exception is thrown at the EndInit method. It says Object reference not set to an instance of an object..
It seems, that Uri is null and it causes the problem. Unfortunately, I cannot find a solution myself.
Display.UriSource? If so, it will ignore theStreamSource. In addition, do you have theCacheOptionproperty set toBitmapCacheOption.OnLoad? EDIT: Also, it appears thatDisplayis a member (field/property), is it possible you have a threading issue here that replaces/changesDisplayas you're working with it?CacheOptionproperty toBitmapCacheOption.OnLoad? Otherwise, from what I understand, it will lazily try to access the stream which may be closed by the time it reads it. According to comments here be sure to set it afterBeginInit(). EDIT: that is:Display = new BitmapImage(); Display.BeginInit(); Display.CacheMode = BitmapCacheOption.OnLoad; Display.StreamSource = ms; Display.EndInit();