// Java Program to implement floodfill algorithm
// in Java Applet(using recursion)
import java.awt.*;
import javax.swing.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.ImageIO;
public class floodfill extends JApplet {
public void init()
{
}
// paint function
public void paint(Graphics g)
{
BufferedImage i = null;
try {
// Input the image to be used for FloodFill
// The output is shown for 3 images
// image1, image2 and image2
i = ImageIO.read(new File("image1.jpg"));
// floodfill with color red at point 35, 35
// get color of image at 35, 35
Color c = new Color(i.getRGB(35, 35));
flood(i, g, 35, 35, c, Color.red);
// draw the image after floodfill
g.drawImage(i, 100, 100, this);
}
catch (Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage());
}
// draw the image after floodfill
g.drawImage(i, 100, 100, this);
}
// function to floodfill the image
public void flood(BufferedImage i,
Graphics g,
int x,
int y,
Color c,
Color c1)
{
if (x >= 1 && y >= 1
&& x < i.getWidth()
&& y < i.getHeight()) {
// find the color at point x, y
Color c2 = new Color(i.getRGB(x, y));
// if there is no boundary (the color is almost
// same as the color of the point where
// floodfill is to be applied
if (Math.abs(c2.getGreen() - c.getGreen()) < 30
&& Math.abs(c2.getRed() - c.getRed()) < 30
&& Math.abs(c2.getBlue() - c.getBlue()) < 30) {
// change the color of the pixel of image
i.setRGB(x, y, c1.getRGB());
g.drawImage(i, 100, 100, this);
// floodfill in all possible directions
flood(i, g, x, y + 1, c, c1);
flood(i, g, x + 1, y, c, c1);
flood(i, g, x - 1, y, c, c1);
flood(i, g, x, y - 1, c, c1);
}
}
}
}