简体   繁体   中英

TextureBrush Out of Memory Exception

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.

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.

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!

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.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM