简体   繁体   中英

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.

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM