Dmitry Korolev
Dmitry Korolev

Reputation: 675

Creating BitmapImage from a byte array

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.

Upvotes: 2

Views: 1756

Answers (2)

Dmitry Korolev
Dmitry Korolev

Reputation: 675

Well, it turned out, that WPF binding was causing the error.

private BitmapImage _display;
public BitmapImage Display
{
    get { return _display; }
    set
    {
        _display = value;
        RaisePropertyChanged("Display");
    }
}

I resolved the issue by getting an image not in the property Display itself, but rather in the filed _display. So, the following is working fine.

using (sc = new ServiceClient())
{
    using (MemoryStream ms = new MemoryStream(sc.GetImage()))
    {
        _display = new BitmapImage();
        _display.BeginInit();
        _display.CacheOption = BitmapCacheOption.OnLoad;
        _display.StreamSource = ms;
        _display.EndInit();
    }
}

Display = _display;

Upvotes: 4

AKD
AKD

Reputation: 3966

u are assigning memory stream directly to the bitmap source, which causes error. first u need to get that array of bytes & than convert it into the memory stream and then assign to the bitmap source, that's it !!!

using (sc = new ServiceClient())
    {
            Byte[] array = sc.GetImage();

            Display = new BitmapImage();
            Display.BeginInit();
            Display.StreamSource = new MemoryStream(array);
            Display.EndInit();
     }

Upvotes: 1

Related Questions