user2320861
user2320861

Reputation: 1431

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

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.
}

Upvotes: 2

Views: 1998

Answers (2)

Steven Hoff
Steven Hoff

Reputation: 91

You might give this library a look.

http://arraysegments.codeplex.com/

Project Description

Lightweight extension methods for ArraySegment, particularly useful for byte arrays.

Supports .NET 4.0 (client and full), .NET 4.5, Metro/WinRT, Silverlight 4 and 5, Windows Phone 7 and 7.5, all portable library profiles, and XBox.

Upvotes: 0

selkathguy
selkathguy

Reputation: 1171

The issue I think is here:

myDataRow.BackgroundImageByteArray = stream.ToArray();

Stream.ToArray() . Be advised, this will convert the stream to an array of bytes with length = stream.Length. Stream.Legnth is size of the buffer of the stream, which is going to be larger than the actual data that is loaded into it. You can solve this by using Stream.ReadByte() in a while loop until it returns a -1, indicating the end of the data within the stream.

Upvotes: 0

Related Questions