TextureBrush Out of Memory Exception

大城市里の小女人 提交于 2019-12-24 07:14:17

问题


I'm trying to place a watermark ontop of another image. This is my code:

var imgPhoto = Image.FromFile(filePath);
var grPhoto = Graphics.FromImage(imgPhoto);

var point = new Point(imgPhoto.Width - imgWatermark.Width, imgPhoto.Height - imgWatermark.Height);

var brWatermark = new TextureBrush(imgWatermark, new Rectangle(point.X, point.Y, imgWatermark.Width, imgWatermark.Height));

grPhoto.FillRectangle(brWatermark, new Rectangle(point, imgWatermark.Size));
imgPhoto.Save(outputFolder + @"\" + filename);

One problem occurs however, the TextureBrush throws an out of memory exception. I've searched around but I couldn't really find a good solution. As far as I can see nothing is disposed before TextureBrush tries to do its job.


回答1:


I am willing to bet that the file at filePath is fairly large.

OutOfMemoryException usually happens when you have .NET heap fragmentation, so here you are probably trying to load a file which is larger than any available block of memory in the Runtime.

Try compressing your image file, or crop it to make it smaller if that is acceptable.

EDIT Try opening your file in an image editor such as MS Paint, or Paint.NET. Then re-save it.

If that doesn't work, try this (basically make sure your rectangle's bounds are inside the watermark image): http://www.owenpellegrin.com/blog/net/out-of-memory-errors-with-gdi-texturebrush/




回答2:


Check the size of your bound area. In your case this will be new Rectangle(point.X, point.Y, imgWatermark.Width, imgWatermark.Height). I had the same "Out of memory" problem and the reason was that my bound area was bigger than my texture size.




回答3:


Also, this can happen when the stream that the Image was loaded from has been disposed. Try to avoid disposing the image stream if you plan on creating a texture brush. For example, this would work:

var bytes = File.ReadAllBytes("image.bmp");
System.Windows.Controls.Image image = null;
using (var stream = System.IO.MemoryStream(bytes))
{
    image = System.Windows.Controls.Image.FromStream(stream);
    var brush = new System.Drawing.TextureBrush(image); // No issues
}

But doing almost the same thing with the mistake of disposing the stream would generate that exception.

var bytes = File.ReadAllBytes("image.bmp");
System.Windows.Controls.Image image = null;
using (var stream = System.IO.MemoryStream(bytes))
{
     image = System.Windows.Controls.Image.FromStream(stream); 
}
var brush = new System.Drawing.TextureBrush(image); // Exception Thrown!



回答4:


You should wrap IDisposable resources in using statements in order to ensure proper disposal as soon as possible. Also don't expect to be able to do a Image.FromFile on files that are bigger than what can fit in memory.



来源:https://stackoverflow.com/questions/11098263/texturebrush-out-of-memory-exception

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