System.OutOfMemoryException 从图像字节数组创建画笔时

System.OutOfMemoryException when creating brush from image byte array

我有时需要像这样从字节数组加载图像:

Bitmap image = null;

using (var ms = new MemoryStream(File.ReadAllBytes(sourceImagePath)))
{
    image = (Bitmap)Image.FromStream(ms);
}

现在我需要从该图像创建一个 TextureBrush,所以我使用以下方法:

using (var b = new TextureBrush(image))
{

}

它抛出 System.OutOfMemoryException: 'Out of memory.'。经过一段时间的试验,我发现如果我像这样使用 Image.FromFile 就可以创建画笔:

using (var b = new TextureBrush(Image.FromFile(sourceImagePath)))
{

}

为简洁起见,我不会深入探讨我不想使用此方法的原因,所以谁能告诉我如何在第一个示例中使用字节数组方法?

删除 MemoryStream 上的 using 语句。

1) MemoryStream 不占用系统资源,不需要处理。您只需关闭流。

2) 当您使用 Image.FromStream 时,您必须保持流打开。见https://docs.microsoft.com/en-us/dotnet/api/system.drawing.image.fromstream?view=netframework-4.7.2的备注部分:

Remarks

You must keep the stream open for the lifetime of the Image.

另一种方法是复制位图,如下所示:

using (var ms = new MemoryStream(File.ReadAllBytes(sourceImagePath)))
using (var bmp = (Bitmap)Image.FromStream(ms))
{
    image = new Bitmap(bmp);
}