创建位图时出现ArgumentException

时间:2014-03-12 14:11:16

标签: c# winforms colors bitmap system.drawing

我目前正在编写一个程序,它创建颜色并将它们输出到pictureBox。我在3D-for循环中执行此操作,以创建所有RGB颜色。所有这些都发生在backgroundWorker中。我的代码如下所示:

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;
        });
      }
    }
  }
}

我正在创建大小为1920x1080的位图。但是在大约220个创建的图像之后,我得到An exception of type 'System.ArgumentException' occurred in System.Drawing.dll当使用较小的尺寸时也会发生这种情况,但是停止工作需要更长的时间。我的代码中有错误吗?

Stack Trace

InnerException为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.

1 个答案:

答案 0 :(得分:3)

当应用程序崩溃时检查任务管理器中的内存使用情况 - 它可能相当大。

每次清理位图 - 否则它们会泄漏一些激烈的东西。

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

    Invoke((MethodInvoker) delegate
    {
            var previousImage = pictureBox1.Image;
        pictureBox1.Image = image;
        if (previousImage != null)
            previousImage.Dispose();
    });
}