2

I am currently creating a little paint program for exercise. Right now i'm trying to do the paint bucket tool, or in other words a flood fill. The funny thing is: if the number of pixels which have to be filled is small, everything works fine. If hate number of to filling pixels is higher, it gives me a SO-Exception. Here is my code:

private void FloodFill(Bitmap picture, int x, int y)
{
  if (x <= 0 || y <= 0 || x >= DrawingPanel.Width || y >= DrawingPanel.Height)
  {
    return;
  }

  if (picture.GetPixel(x, y) != löschFarbe)
  {
    return;
  }

  if (picture.GetPixel(x, y) == löschFarbe)
  {
    picture.SetPixel(x, y, ColorButton.BackColor);
  }

  FloodFill(picture, x + 1, y);
  FloodFill(picture, x, y + 1);
  FloodFill(picture, x - 1, y);
  FloodFill(picture, x, y - 1);
  FloodFill(picture, x + 1, y + 1);
  FloodFill(picture, x - 1, y + 1);
  FloodFill(picture, x + 1, y - 1);
  FloodFill(picture, x - 1, y - 1);
}

"löschFarbe" is the color which is clicked (which will be erased/overwritten with another color)

Error occurring: If i want to fill the complete picture or a big space, I get an error here:

if (picture.GetPixel(x, y) != löschFarbe)
  {
    return;
  }

Anyone knows how I can solve this?

BTW this is a picture of my program: Paint

Sreenath S
  • 1,269
  • 1
  • 14
  • 21
Tim Kathete Stadler
  • 1,067
  • 4
  • 26
  • 52
  • 1
    You're getting the stack overflow exception because your `FloodFill` calls itself too many times. Consider how many pixels there are in your image, then consider how many times `FloodFill` will be called when you click in the centre of your image. It calls `FloodFill`, which then calls `FloodFill` on the first adjacent pixel, and that one does the same, over and over and over. – dreamlax Jan 08 '13 at 10:06
  • You are getting the error somewhere else because the `GetPixel` method doesn't have enough stack space to work properly. You need to rethink how to do a flood fill using loops rather than recursion. – dreamlax Jan 08 '13 at 10:07
  • Geez an 8 point exponential, 1 - 8 - 64 -512 - 4096 - 32768, no wonder you got a stack overflow! thats just to a depth of 6 0.o – RhysW Jan 08 '13 at 10:20

1 Answers1

3

Even a moderate sized floodfill will blow your call stack.

Try converting this recursion based method to a stack based method as in this question.

Community
  • 1
  • 1
Nicolas Repiquet
  • 9,097
  • 2
  • 31
  • 53