Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 从图像字节数组创建画笔时System.OutOfMemoryException_.net_Drawing_Gdi+ - Fatal编程技术网

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

.net 从图像字节数组创建画笔时System.OutOfMemoryException,.net,drawing,gdi+,.net,Drawing,Gdi+,我有时需要从字节数组加载图像,如下所示: Bitmap image = null; using (var ms = new MemoryStream(File.ReadAllBytes(sourceImagePath))) { image = (Bitmap)Image.FromStream(ms); } using (var b = new TextureBrush(Image.FromFile(sourceImagePath))) { } 现在我需要从该图像创建一个Textu

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

Bitmap image = null;

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

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

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

}
它抛出System.OutOfMemoryException:“内存不足”。。经过一段时间的实验,我发现如果我像这样使用
Image.FromFile
可以创建笔刷:

Bitmap image = null;

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

}

为简洁起见,我不想讨论我不想使用此方法的原因,因此有人能告诉我如何使用第一个示例中的字节数组方法吗?

删除MemoryStream上的using语句

1) MemoryStream不占用任何系统资源,因此不需要处理它们。你只要把小溪关上

2) 使用Image.FromStream时,必须使流保持打开状态。见以下备注部分:

备注

您必须在映像的生命周期内保持流打开

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

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

删除MemoryStream上的using语句

1) MemoryStream不占用任何系统资源,因此不需要处理它们。你只要把小溪关上

2) 使用Image.FromStream时,必须使流保持打开状态。见以下备注部分:

备注

您必须在映像的生命周期内保持流打开

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

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

太棒了,我从来没有想过要像上一个例子那样复制流位图。它很好用,所以我会用它。我很高兴这个选项存在,因为我不喜欢使用
IDisposable
对象而不使用
使用
。他们现在可能不使用系统资源或不需要清理,但是,如果将来发生变化,您可以放心,您将不需要重构任何代码。很高兴我能提供帮助。太棒了,我从来没有想过要像上一个示例中那样复制流位图。它很好用,所以我会用它。我很高兴这个选项存在,因为我不喜欢使用
IDisposable
对象而不使用
使用
。他们可能不使用系统资源,或者现在不需要清理,但是,如果将来发生变化,您可以放心,您将不需要重构任何代码。很高兴我能提供帮助。