Extract a selected polygon from an image to a new image file in Java

A reference code to extract a selected shape (this case polygon, could be another shape like Rectangle) –


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.drawImage(in, -bounds.x, -bounds.y, null);

File extImageFile = new File(targetFilePath);

ImageIO.write(extractor, "png", extImageFile);


Kj [/.] Sreekumar programs computers as a hobby and profession. Into programming from his school days, Sree uses Codemarvels to key in facts and fixes he finds interesting while working on different projects. Some of the articles here give away a few shades of his philosophical leanings too.

Leave a Comment

Your email address will not be published. Required fields are marked *