将保存的字节数组加载到内存流会导致内存不足异常

时间:2014-02-25 21:21:26

标签: c# image bitmap out-of-memory memorystream

在我的程序中的某个时刻,用户选择一个位图作为Panel对象的背景图像。当用户执行此操作时,程序会立即使用背景图像绘制面板,一切正常。当用户单击" Save"时,以下代码将位图保存到DataTable对象。

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

一切正常,此流没有内存不足异常,即使它包含所有图像字节。但是,当应用程序启动并加载已保存的数据时,以下代码会引发内存不足异常:

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

流的长度相同。我不明白如何抛出一个内存不足的异常而另一个没有。如何加载此位图?

P.S。我也试过了

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

2 个答案:

答案 0 :(得分:0)

我认为这个问题在这里:

myDataRow.BackgroundImageByteArray = stream.ToArray();

Stream.ToArray()。请注意,这会将流转换为长度= stream.Length的字节数组。 Stream.Legnth是流的缓冲区大小,它将大于加载到其中的实际数据。您可以在Stream.ReadByte()循环中使用while来解决此问题,直到它返回-1,表示流中数据的结束。

答案 1 :(得分:0)

你可以看看这个库。

http://arraysegments.codeplex.com/

项目说明

ArraySegment的轻量级扩展方法,对字节数组特别有用。

支持.NET 4.0(客户端和完整版),.NET 4.5,Metro / WinRT,Silverlight 4和5,Windows Phone 7和7.5,所有可移植库配置文件和XBox。

相关问题