gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:59:30 25 4
gpt4 key购买 nike

在我的程序中的某个时刻,用户选择一个位图用作 Panel 对象的背景图像。当用户这样做时,程序会立即绘制带有背景图像的面板,一切正常。当用户单击“保存”时,以下代码将位图保存到 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);
}

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

附言我也试过

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

最佳答案

我觉得问题出在这里:

myDataRow.BackgroundImageByteArray = stream.ToArray();

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

关于c# - 将保存的字节数组加载到内存流导致内存不足异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22026481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com