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.

Community
  • 1
  • 1
user3363744
  • 167
  • 1
  • 9

1 Answers1

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

//.. 
Khalil Khalaf
  • 9,259
  • 11
  • 62
  • 104
  • Thank you that worked. I was under the assumption that BitmapImage[] bmpi = new BitmapImage[1] initialized the objects in the array – user3363744 Aug 26 '16 at 17:41
  • 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**](http://stackoverflow.com/questions/648814/direct-array-initialization-with-a-constant-value) – Khalil Khalaf Aug 26 '16 at 17:44