Reputation: 1069
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?
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.
Upvotes: 1
Views: 2050
Reputation: 6689
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();
});
}
Upvotes: 3