Loading saved byte array to memory stream causes out of memory exception

Posted by user2320861 on Stack Overflow See other posts from Stack Overflow or by user2320861
Published on 2014-02-25T21:21:26Z Indexed on 2014/08/24 22:20 UTC
Read the original article Hit count: 234

Filed under:
|
|
|
|

At some point in my program the user selects a bitmap to use as the background image of a Panel object. When the user does this, the program immediately draws the panel with the background image and everything works fine. When the user clicks "Save", the following code saves the bitmap to a DataTable object.

MyDataSet.MyDataTableRow myDataRow = MyDataSet.MyDataTableRow.NewMyDataTableRow(); //has a byte[] column named BackgroundImageByteArray
using (MemoryStream stream = new MemoryStream())
{
    this.Panel.BackgroundImage.Save(stream, ImageFormat.Bmp);
    myDataRow.BackgroundImageByteArray = stream.ToArray();
}

Everything works fine, there is no out of memory exception with this stream, even though it contains all the image bytes. However, when the application launches and loads saved data, the following code throws an Out of Memory Exception:

using (MemoryStream stream = new MemoryStream(myDataRow.BackGroundImageByteArray))
{
    this.Panel.BackgroundImage = Image.FromStream(stream);
}

The streams are the same length. I don't understand how one throws an out of memory exception and the other doesn't. How can I load this bitmap?

P.S. I've also tried

using (MemoryStream stream = new MemoryStream(myDataRow.BackgroundImageByteArray.Length))
{
    stream.Write(myDataRow.BackgroundImageByteArray, 0, myDataRow.BackgroundImageByteArray.Length); //throw OoM exception here.
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about image