vendredi 17 avril 2015

g.DrawImage throws out of memory exception

In my aplication I am working with about 30 - 70 large images. By working I mean loading, cropping, resizing and adding to aviStream. Each image can have up to 4500p and 10MB (working with such large images gives me most of the out of memory exceptions). While testing I sometimes use smaller ones (2500p ~ 500kB each) and the memory situation is much better.


I have changed the architecture of my program to: load one image, process the needed operations, add it to the stream, close it. And doing the same with next image. But due to the complexity and size of the code, I am not 100% sure that I dispose and close every bitmap and image created for temporary purposes during this proces.


I have the following error:



An unhandled exception of type 'System.OutOfMemoryException' occurred in System.Drawing.dll


Usually when cropping image:



public static Image Crop(Image imgPhoto, Point xy, int width, int height) {
Rectangle cropRect = new Rectangle(xy, new Size(width, height));
Bitmap target = new Bitmap(cropRect.Width, cropRect.Height);

using (Graphics g = Graphics.FromImage(target)) {
g.DrawImage(imgPhoto, new Rectangle(0, 0, target.Width, target.Height), cropRect, GraphicsUnit.Pixel);
}

return target;
}


The exception is thrown based on the cropping level, if I crop small part of an large image, lets say 800x600 pixels in the middle, it is better. If a crop in the oposite way, lets say create an 3500x2500 image where the original image is smaller (blank space will be automaticaly filled with selected color), I have the exception most of the time.


One interesting thing is also that the exception is thrown around 23rd image, so previous images are procesed fine.


Can you guys give me an advice how to debug this? I have tried to scan the code for undisposed images and bitmaps, but it seems that I haven't found all of them.


The big question therefore is: How to proces all images one by one without having an exception?


Aucun commentaire:

Enregistrer un commentaire