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

4.5k views Asked by At

I'm trying to loop through all the images I load, I'm able to process up to 40 images, then the I get the Out of memory error although I'm disposing the variable tempImage. The code breaks at the "Bitmap tempImage = new Bitmap(fileName);" line, plz help! Is there a way to handle large number of input files? Like batch process and splitting the process into chunks? Because the operation would last more than a minute to finish, the program would crash by then.

foreach (string fileName in openFileDialog.FileNames)
{
    circleDetection examDetect = new circleDetection();
    Bitmap tempImage = new Bitmap(fileName);
    directory.Text = fileName;

    PictureBox picBox = new PictureBox();
    picBox.Width = 200;
    picBox.Height = 200;
    picBox.Location = new System.Drawing.Point(picBoard.Controls.Count * (picBox.Width + 5) + 5, 5);
    picBox.SizeMode = PictureBoxSizeMode.Zoom;
    picBox.BorderStyle = BorderStyle.FixedSingle;
    examDetect.ProcessImage(tempImage);
    picBox.Image = examDetect.getImage();

    Console.WriteLine(i++);

    student.Add(compare(examDetect));
    picBoard.Controls.Add(picBox);
    tempImage.Dispose();
}
1

There are 1 answers

0
Andrey Carter On

I prefer to use using() instead of .Dispose(). It's also disposing an object after it's cycle ended. So maybe you should try smth like next?

foreach (string fileName in openFileDialog.FileNames)
{
    circleDetection examDetect = new circleDetection();
    using (Bitmap tempImage = new Bitmap(fileName))
    {
        Exam.Add(tempImage);
        directory.Text = fileName;

        PictureBox picBox = new PictureBox();
        picBox.Width = 200;
        picBox.Height = 200;
        picBox.Location = new System.Drawing.Point(picBoard.Controls.Count * (picBox.Width + 5) + 5, 5);
        picBox.SizeMode = PictureBoxSizeMode.Zoom;
        picBox.BorderStyle = BorderStyle.FixedSingle;
        examDetect.ProcessImage(tempImage);
        picBox.Image = examDetect.getImage();

        Console.WriteLine(i++);

        student.Add(compare(examDetect));
        picBoard.Controls.Add(picBox);
    }
}

See MSDN for more information about using statement.

UPDATE: But, why don't you use stream for loading your files? It's recommended to use stream for such cases.