0

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.

0

1 Answer 1

2

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

//.. 
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you that worked. I was under the assumption that BitmapImage[] bmpi = new BitmapImage[1] initialized the objects in the array
You declared your array and set its size. That does not do more than what you think it does. To initialize all elements you will need to loop your container and set each element. Glad we were able to help :) See the loop Here

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.