user3363744
user3363744

Reputation: 169

BitmapImage array issue

I'm having trouble understanding why im getting an error when I change my BitmapImage from a single object into an array of objects.

When I create a single bmpi (BitmapImage) object everything works great.

public BitmapImage retrieveImageFromDataBase(int ID)
    {
        //Get the byte array from the database using the KEY     
        STOREDIMAGE insertedImage = dc.STOREDIMAGEs.FirstOrDefault(z => z.ID.Equals(ID));
        //convert byte stream into bitmap to display in WPF image box
        BitmapImage bmpi = new BitmapImage();
        bmpi.BeginInit();
        bmpi.StreamSource = new MemoryStream(insertedImage.IMAGES.ToArray());
        bmpi.EndInit();
        return bmpi;
    }

When I set my bitmapImage to an array (in this case i set it to an array of 1 to show the error) I get the error at the BeginInit() method of the BitmapImage object

An unhandled exception of type 'System.NullReferenceException' occurred in FHPictureViewer.exe

Additional information: Object reference not set to an instance of an object.

public BitmapImage[] retrieveImageFromDataBase(int ID)
    {
        //Get the byte array from the database using the KEY     
        STOREDIMAGE insertedImage = dc.STOREDIMAGEs.FirstOrDefault(z => z.ID.Equals(ID));
        //convert byte stream into bitmap to display in WPF image box
        BitmapImage[] bmpi = new BitmapImage[1];
        bmpi[0].BeginInit();
        bmpi[0].StreamSource = new MemoryStream(insertedImage.IMAGES.ToArray());
        bmpi[0].EndInit();
        return bmpi;
    }

I can't wrap my head around whats happening. Seems like it should be the same thing.

Upvotes: 0

Views: 391

Answers (1)

Khalil Khalaf
Khalil Khalaf

Reputation: 9407

You did not initialize the elements in your array, which is a single element in your case.

This should work:

// .. 

BitmapImage[] bmpi = new BitmapImage[1];
bmpi[0] = new BitmapImage();
bmpi[0].BeginInit();

//.. 

Upvotes: 2

Related Questions