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);

Leave a Reply

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


* Copy This Password *

* Type Or Paste Password Here *

68,488 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>