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

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

在我的程序中的某个时刻,用户选择一个位图用作 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/

相关文章:

android - 在 Google Maps v2 for Android 中自定义标记上的可点击区域

android - 如何在webview中截取 map 的截图

c# - 定期更换桌面墙纸

css - 相对于其他元素居中文本?

ios - 访问核心数据镜像中的外部数据引用属性

java - 使用 Glide 加载位图到 ImageView

c# - 与 Funcs 的组合是否优于继承以更改单个函数中的行为?

c# - 使用 IServiceCollection.AddSingleton() 的单个对象实例

c# - 列表在调试器中显示 4 个项目,即使只填充了一个元素

c# - 使用内存映射 View 查看大位图图像