A reference code to extract a selected shape (this case polygon, could be another shape like Rectangle) –
[java]
BufferedImage in = ImageIO.read(new File(sourceFilePath));
Rectangle bounds = inputPolygon.getBounds(); // Polygon inputPolygon
BufferedImage extractor =new BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = extractor.createGraphics();
polygon.translate(-bounds.x, -bounds.y);
g.setClip(polygon);
g.drawImage(in, -bounds.x, -bounds.y, null);
File extImageFile = new File(targetFilePath);
ImageIO.write(extractor, “png”, extImageFile);
[/java]

Sreekumar (KJ) has been a hobby programmer from school days. Codemarvels is his personal blog from the year 2010, where he writes about technology, philosophy, society and a bit about physics.
He now runs a conversational AI company – DheeYantra – focusing his efforts to help businesses improve operational efficiency using digital employees powered by AI.