1

I am currently writing a programm, which creates colors and outputs them to a pictureBox. I am doing this in a 3D-for loop, to create all RGB colors. All this happens in a backgroundWorker. My code looks like this:

private void ColorWorker_DoWork(object sender, DoWorkEventArgs e)
{
  Color color;
  String hex;
  Bitmap image;

  Invoke((MethodInvoker)delegate
  {
    progressBar1.Maximum = (255 * 255 * 255);
    progressBar1.Value = 0;
  });

  for (int r = 0; r <= 255; r++)
  {
    for (int g = 0; g <= 255; g++)
    {
      for (int b = 0; b <= 255; b++)
      {
        hex = "#FF" + r.ToString("X2") + g.ToString("X2") + b.ToString("X2");
        color = System.Drawing.ColorTranslator.FromHtml(hex);
        image = new Bitmap((int)nudWidth.Value, (int)nudHeight.Value);

        using (Graphics gfx = Graphics.FromImage(image))
        using (SolidBrush brush = new SolidBrush(color))
        {
          gfx.FillRectangle(brush, 0, 0, image.Width, image.Height);
        }             

        Invoke((MethodInvoker)delegate
        {
          pictureBox1.Image = image;
          progressBar1.Value++;
          label13.Text = progressBar1.Value + " / " + progressBar1.Maximum;
        });
      }
    }
  }
}

I am creating Bitmaps of the size 1920x1080. But after around 220 created images, I get An exception of type 'System.ArgumentException' occurred in System.Drawing.dll This also happens when using lower sizes, but then it takes longer to stop working. Is there an error in my code?

Stack Trace

InnerException is NULL

An exception of type 'System.ArgumentException' occurred in System.Drawing.dll but was not handled in user code

Additional information: Invalid Parameter.

If there is a handler for this exception, the program may be safely continued.
2
  • Is it possible you post the full exception including message, inner exceptions and stacktraces here? And please indicate on which line of your example code the exception occurs. Commented Mar 12, 2014 at 14:15
  • added some stuff hope it enough Commented Mar 12, 2014 at 14:23

1 Answer 1

3

Check your memory usage in Task Manager when the application crashes - it is probably rather large.

Clean up the bitmaps each time - otherwise they are leaking something fierce.

Bitmap previousImage = null;
for(r... g... b...)
{
    // ...

    Invoke((MethodInvoker) delegate
    {
            var previousImage = pictureBox1.Image;
        pictureBox1.Image = image;
        if (previousImage != null)
            previousImage.Dispose();
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.