从图像字节数组创建画笔时发生System.OutOfMemoryException [英] System.OutOfMemoryException when creating brush from image byte array

查看:63
本文介绍了从图像字节数组创建画笔时发生System.OutOfMemoryException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我需要从字节数组中加载图像,如下所示:

I sometimes need to load an image from a byte array like this:

Bitmap image = null;

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

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

Now I need to create a TextureBrush from that image, so I use the following approach:

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

}

它抛出 System.OutOfMemoryException:内存不足。 。经过一段时间的试验,我发现如果使用 Image.FromFile 这样的话,就可以创建画笔:

It throws System.OutOfMemoryException: 'Out of memory.'. After a while of experimenting, I've found that I can create the brush if I use Image.FromFile like this:

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

}

为简便起见,我不会介绍我不想使用此方法的原因,因此任何人都可以告诉我如何使用第一个示例中的字节数组方法?

For brevity, I will not go into the reason why I do not want to use this method, so can anyone show me how I can use the byte array approach in the first example?

推荐答案

删除MemoryStream上的using语句。

Remove the using statement on the MemoryStream.

1)MemoryStream不会占用任何系统资源,因此不需要处理它们。

1) A MemoryStream does not take up any system resources, so there is no need disposing them. You just close the stream.

2)使用Image.FromStream时,必须保持流打开。请参阅 https://docs.microsoft.com/zh-cn/dotnet/api/system.drawing.image.fromstream?view=netframework-4.7.2

2) When you use Image.FromStream you must leave the stream open. See the remarks section on https://docs.microsoft.com/en-us/dotnet/api/system.drawing.image.fromstream?view=netframework-4.7.2:


备注

在图像的整个生命周期中必须保持流打开。

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

另一种选择是复制位图,如下所示:

Another alternative would be to copy the bitmap, like so:

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

这篇关于从图像字节数组创建画笔时发生System.OutOfMemoryException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆