@Controller public class BackgroundRemoverController { @GetMapping("/") public String index() { return "index"; } @PostMapping("/remove-bg") public String removeBg(@RequestParam("file") MultipartFile file, Model model) { try { // Convert the file to a BufferedImage BufferedImage image = ImageIO.read(file.getInputStream()); // Convert the image to grayscale BufferedImage grayImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_GRAY); Graphics g = grayImage.getGraphics(); g.drawImage(image, 0, 0, null); g.dispose(); // Apply a threshold to the image to create a binary image BufferedImage binaryImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_BINARY); g = binaryImage.getGraphics(); g.drawImage(grayImage, 0, 0, null); g.dispose(); // Find the contours in the binary image List contours = findContours(binaryImage); // Create a black image BufferedImage result = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB); // Draw the contours on the image Graphics2D g2d = result.createGraphics(); g2d.setColor(Color.WHITE); contours.forEach(contour -> g2d.fillPolygon(contour, contour.length)); g2d.dispose(); // Save the result ImageIO.write(result, "jpg", new File("result.jpg")); model.addAttribute("message", "Background removed!"); } catch (IOException e) { model.addAttribute("message", "An error occurred: " + e.getMessage()); } return "index"; } private List findContours(BufferedImage image) { // ... } }