问题
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