System.OutOfMemoryException when creating brush from image byte array

穿精又带淫゛_ 提交于 2019-12-11 15:30:11

问题


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);
}

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

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

}

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?


回答1:


Remove the using statement on the MemoryStream.

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

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:

Remarks

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);
}


来源:https://stackoverflow.com/questions/54085438/system-outofmemoryexception-when-creating-brush-from-image-byte-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!