I have a Java program containing an image, and I'm trying to have a flood fill agorithm to repleace each black pixel with a white one within the enclosed area, using the following function(canvas
is a BufferedImage
):
public void floodFill(Point2i start, int target, int grep){
if(start.x < 0 || start.x >= width || start.y < 0 || start.y >= height)return;
if(canvas.getRGB(start.x, start.y) != target)return;
canvas.setRGB(start.x, start.y, grep);
floodFill(new Point2i(start.x+1, start.y), target, grep);
floodFill(new Point2i(start.x-1, start.y), target, grep);
floodFill(new Point2i(start.x, start.y+1), target, grep);
floodFill(new Point2i(start.x, start.y-1), target, grep);
}
Problem is, I get a java.lang.StackOverflowError
on the third line.... I figure there must be a better way to do this that doesn't cause this error, isn't there? I'm running the JVM with a decent amount of RAM(2 GB), so how can I write a flood fill function for a BufferedImage that works?